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;
7
  • On which line exactly? Did you debug your code? Related: What is a NullReferenceException and how do I fix it? Commented Apr 20, 2015 at 14:19
  • dr[rownumber] = dt.NewRow(); Commented Apr 20, 2015 at 14:19
  • yeah i already did it. Made thorough search. after all searching and scratching i end up asking you people Commented Apr 20, 2015 at 14:22
  • How did you define dr? Commented Apr 20, 2015 at 14:23
  • DataRow dr; DataTable dt; Commented Apr 20, 2015 at 14:25

2 Answers 2

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

3 Comments

Nice to see your back on WPF
@TalhaIrfan :) I didn't go anywhere, I just got busy and don't have as much time for SO. Thanks though!
Thank you so much for still finding some time for SO. We are grateful for any time you give here :)
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.

Comments

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.