Adding rows to table not connected to database

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.
 
N

Nicholas Paldino [.NET/C# MVP]

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.
 
I

Ignacio Machin \( .NET/ C# MVP \)

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,
 
A

Arek

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!
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top