2

I want to set number of rows of datagrid equal to a number given by user in a textbox. means if i enter 6 in the textbox, it should add 6 rows in the datagrid. thats what i want. I may be wrong. But Null exception is being thrown. How to fix my issue?

Here is the code:

          DataTable dt;
          DataRow dr;
        int rownumber=0;
        dt = new DataTable("emp2");
        DataColumn dc3 = new DataColumn("Wi", typeof(double));
        DataColumn dc4 = new DataColumn("Hi", typeof(double));

        rownumber = Int32.Parse(txtBexNumber.Text);
        dr[rownumber] = dt.NewRow();
        dt.Rows.Add(dr);
        dt.Columns.Add(dc3);
        dt.Columns.Add(dc4);

        datagrid1.ItemsSource = dt.DefaultView;
Vanadium90
  • 111
  • 6

2 Answers2

3

You're creating a DataTable, then trying to immediately access a user-specified row in the table even though no rows have been added yet.

Use a loop to add rows first

for(int i = 0; i < rowNumber; i++)
{
    dr = dt.NewRow();
    dt.Rows.Add(dr);
}

As a side note, when working with WPF its easier to work with an ObservableCollection of objects instead of DataTables and DataRows. The data is much easier to understand and work with instead of trying to use DataRows and DataColumns.

var data = new ObservableCollection<MyObject>();

for (int i = 0; i < rowNumber; i++)
    data.Add(new MyObject() { Wi = 0, Hi = 0 });

dataGrid1.ItemsSource = data;
Rachel
  • 122,023
  • 59
  • 287
  • 465
0

I guess it´s better to use

Int32.TryParse(txtBexNumber.Text, out rownumber);

(maybe you get the error for parsing an empty string? If possible try to debug where exactly the null pointer exception accurs)

Also validate if

dr[rownumber] = dt.NewRow();

works as expected. If e.g. dr[10] doesn´t exist, you get an exception.

Ben
  • 857
  • 5
  • 11