Jon Jon - 1 year ago 166
C# Question

DataTable NullReferenceException

So I have looked through as much reference and previous questions as possible and I can't seem to find the answer, or I may not be understanding it. I have the below code:

public DataSet dsFilter = new DataSet();
public DataTable dtFilter = new DataTable();

public frmFilter()
cbFilter.SelectedIndex = 0;
this.dsFilter.Tables[0].TableName = "tr_filtered";

public void SetupFilter()
lblRecs.Text = this.dsFilter.Tables["tr_filtered"].Rows.Count + "recs";

public void LoadListBox(string colName)
DataTable dt = this.dsFilter.Tables["tr_filtered"];

if (dt.Rows.Count > 0)
for (int i = 0; i != dt.Rows.Count; i++) { lbFilter.Items.Add(dt.Rows[i][colName]); }
object[] items = new object[lbFilter.Items.Count];
lbFilter.Items.CopyTo(items, 0);

However, I am getting a System.NullReferenceException on the below line:

if (dt.Rows.Count > 0)

From what I have looked at, this error typically only occurs when not initializing, but I thought that I was initializing the DataTable and DataSet correctly. I mean, apparently I'm not and I am hoping somebody can help me or at least point me in the right direction.

Answer Source

The main reason for this is there is no defined columns for this table hence the Rows became null or undefined if you add some columns means you will get and access the rows. Try something like this:

dtFilter.TableName = "tr_filtered";
// add few colums as per the requirements

Or you can check for existance of rows before accessing them, which is like this:

if (dt.Rows != null && dt.Rows.Count > 0)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download