When loading Excel files in my Windows Form application, I can load .xls
and .xlsx
formats fine but when I select a .CSV
I get the following error:
System.NullReferenceException: 'Object reference not set to an instance of an object.' sConnectionString was null.
The error happens on the line:
if (sConnectionString.Length > 0)
From the full section of code:
public string sConnectionString;
public void FillData()
{
if (sConnectionString.Length > 0)
{
OleDbConnection cn = new OleDbConnection(sConnectionString);
{
cn.Open();
DataTable dt = new DataTable();
OleDbDataAdapter Adpt = new OleDbDataAdapter("select * from [sheet1$]", cn);
Adpt.Fill(dt);
dataGridView1.DataSource = dt;
}
}
}
Which is before the Button code:
private void Browse_Click(object sender, EventArgs e)
{
OpenFileDialog op = new OpenFileDialog();
op.InitialDirectory = @"C:\";
op.Title = "Browse Excel Files";
op.CheckFileExists = true;
op.CheckPathExists = true;
op.DefaultExt = "csv";
op.Filter = "CSV Files (*.csv)|*.csv";
op.FilterIndex = 2;
op.RestoreDirectory = true;
op.ReadOnlyChecked = true;
op.ShowReadOnly = true;
if (op.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
if (File.Exists(op.FileName))
{
string[] Arr = null;
Arr = op.FileName.Split('.');
if (Arr.Length > 0)
{
if (Arr[Arr.Length - 1] == "xls")
sConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" +
op.FileName + ";Extended Properties='Excel 8.0;HDR=Yes;IMEX=1'";
}
else if (Arr[Arr.Length - 1] == "xlsx")
{
sConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + op.FileName + ";Extended Properties='Excel 12.0 Xml;HDR=YES';";
}
}
FillData();
fileTextBox.Text = op.FileName;
}
}
Edit
Added:
else if (Arr[Arr.Length - 1] == "csv")
{
sConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + op.FileName +
";Extended Properties='Excel 8.0;HDR=Yes;IMEX=1'";
}
Still get the same error.