我试图了解使用以下方法创建的行之间的区别:
newTable.Rows.Add(array);
newTable.ImportRow(row);
我有一个 WinForms 应用程序,它使用这两种方法将行添加到 DataTable。现在,当我将该 DataTable 用作 DataGridView 的数据源时,我可以看到使用这两种方法创建的“所有”行。但是,当我使用类型的循环时
foreach (DataRow row in newTable.Rows)
{
//...do work
}
循环仅“看到”使用 ImportRow 方法创建的行。好像使用 Rows.Add(array) 创建的行不存在,但显然它们确实存在,因为当我使用 DataTable 作为其数据源时,我可以在 DataGridView 中看到它们。
编辑(随后由 Rahil Jan Muhammad 发表评论)
是的 - 在玩了很多之后,我认为行添加方法与它无关。问题出在以下代码中:
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;
}
}
第一个循环使除“分配”列之外的所有列都是只读的。如果“活动”列中的值为假,则第二个循环旨在使“分配”列甚至为只读。然而,正在发生的事情恰恰相反。Active 为 true 的那些行是只读的,反之亦然。所以是的,我的“if”语句有问题。但是什么?