Jon Jon - 1 month ago 16
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()
{
InitializeComponent();
cbFilter.SelectedIndex = 0;
this.dsFilter.Tables.Add(dtFilter);
this.dsFilter.Tables[0].TableName = "tr_filtered";
}

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

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

if (dt.Rows.Count > 0)
{
lbFilter.Items.Clear();
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);
lbFilter.Items.Clear();
lbFilter.Items.AddRange(items.AsEnumerable().Distinct().ToArray());
}
}


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

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";
dtFilter.Columns.Add("column1");
dtFilter.Columns.Add("column2");
// add few colums as per the requirements
dsFilter.Tables.Add(dtFilter);

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

if (dt.Rows != null && dt.Rows.Count > 0)
Comments