Adding rows to table not connected to database

  • Thread starter Thread starter Arek
  • Start date Start date
A

Arek

I need to have a simple table. User and application will add rows to it.
I've used DataGrid but I can't add rows by application. I've got such code:
DataRow row = dataTable.NewRow();
row.BeginEdit();
row.ItemArray.SetValue("0", 0);
row.ItemArray.SetValue("0", 1);
row.ItemArray.SetValue("0", 2);
row.ItemArray.SetValue("0", 3);
row.EndEdit();
dataRow.ImportRow(row);
dataGrid.DataSource = dataTable;
But this have no effect - dataGrid is empty. Is in C# another component
to display tables? How should it be to work properly?
Thanks for help.
 
Arek,

Well, the row is added, but the values themselves are empty. ItemArray
returns a copy of the array of items which represent the values in the
columns. Because of this, when you call SetValue, you are changing the
value of the array on four different arrays.

What you need to do is use the indexer for the row, and set the value
with the column name, like this:

DataRow row = dataTable.NewRow();
row.BeginEdit();
row[0] = 0;
row[1] = 0;
row[2] = 0;
row[3] = 0;
row.EndEdit();
dataRow.ImportRow(row);
dataGrid.DataSource = dataTable;

Hope this helps.
 
Use this code :
DataRow row = dataTable.NewRow();
row[0] = 0;
row[1] = 1;
row[2] = 2;
row[3] = 3;
dataTable.Rows.Add( row);
dataGrid.DataSource = dataTable;
dataGrid.Bind();

cheers,
 
Nicholas Paldino [.NET/C# MVP] napisa³(a):
Arek,

Well, the row is added, but the values themselves are empty. ItemArray
returns a copy of the array of items which represent the values in the
columns. Because of this, when you call SetValue, you are changing the
value of the array on four different arrays.

What you need to do is use the indexer for the row, and set the value
with the column name, like this:

DataRow row = dataTable.NewRow();
row.BeginEdit();
row[0] = 0;
row[1] = 0;
row[2] = 0;
row[3] = 0;
row.EndEdit();
dataRow.ImportRow(row);
dataGrid.DataSource = dataTable;

Hope this helps.
Oh ... I blame myself :) That was so easy ... Thank you!
 
Back
Top