I’m trying to understand the difference between rows created using the following methods:
newTable.Rows.Add(array);
newTable.ImportRow(row);
I have a WinForms App which uses both these methods to add rows to a DataTable.
Now when I use that DataTable as the DataSource for a DataGridView I can see ‘all’ of the rows created using both methods.
However, when I use a loop of the type
foreach (DataRow row in newTable.Rows)
{
//...do work
}
The loop only ‘sees’ the rows created using the ImportRow method. Its as if the rows created using the Rows.Add(array) don’t exist, yet clearly they do because I can see them in the DataGridView when I use the DataTable as its DataSource.
EDIT (subsequent to comment by Rahil Jan Muhammad)
Yes – after a lot of playing around I think the Row Adding Methods are nothing to do with it. The issue is in the following code:
foreach (DataGridViewColumn col in dataAllocations.Columns)
{
if (col.Name == "Allocation")
{
col.ReadOnly = false;
}
else
{
col.ReadOnly = true;
}
}
foreach (DataGridViewRow row in dataAllocations.Rows)
{
MessageBox.Show("DataGrid, " + row.Cells["AllocID"].Value.ToString() +
", " + row.Cells["Active"].Value.ToString());
if (row.Cells["Active"].Value == null || (bool)row.Cells["Active"].Value == false)
{
row.ReadOnly = true;
}
else
{
row.ReadOnly = false;
}
}
The first loop makes all Columns except Column “Allocation” read only. The second loop is intended to make even Column “Allocation” read only, if the value in Column “Active” is false. However what is happening is exactly the opposite. Those rows where Active is true are read only and vice versa. So yes, there is something wrong with my ‘if’ statement. But what?
I found your problem(logig error):
}
your code sets the all row’s column readonly.you want to set readonly Allocation column(my code).