1

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.

2
  • Change the test to be this: if (dt != null && dt.Rows.Count > 0) Commented Nov 4, 2016 at 3:56
  • 1
    That worked! Thank you so much! Honestly, I should've caught that. Commented Nov 4, 2016 at 4:00

1 Answer 1

2

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)
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, I went ahead and updated the test and it worked!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.