为什么数据视图在"AllowEdit=true"时仍然是只读的?



我有代码(下面),我认为应该允许我更新基础表,但我继续收到"基础数据是只读的"错误。

在下面的代码中,包括我尝试过的所有内容。 显然,我错过了一些东西! 在SO中搜索没有找到线索...

APT.Columns["Selected"].ReadOnly = false;
TWR.Columns["Selected"].ReadOnly = false;
RWY.Columns["Selected"].ReadOnly = false;
APT.Columns["Selected"].Expression = "false";
TWR.Columns["Selected"].Expression = "false";
RWY.Columns["Selected"].Expression = "false";
// DataView with filtered "parent" table data
// Apply user's filter for the "Fix"
DataView dataView = new DataView(APT)
{
RowFilter = FixFilter(chkboxShowAll.Checked),
Sort = "FacilityID",
AllowEdit = true,
};
// RWY and TWR dont have ARTCC (filter item), 
// so we can't filter by that, 
// and "Join" makes the table readonly, 
//so must grab root ID and change manually
DataView dvTWR = new DataView(TWR)
{
AllowEdit = true                 // Enable editing
};
DataView dvRWY = new DataView(RWY)
{
AllowEdit = true
};
// TWRs and RWYs have the same ID as the APT, 
// but not may have a TWY or RWY (e.g., Seabase)
// This should update the "Selected" boolean 
foreach (DataRowView dataRowView in dataView)
{
dataRowView.BeginEdit();
dataRowView["Selected"] = true;  // *** <- EXCEPTION HERE
dataRowView.EndEdit();
int result = dvRWY.Find(dataRowView["ID"]);
if (result != -1)
{
dvRWY[result].BeginEdit();
dvRWY[result]["Selected"] = true;
dvRWY[result].EndEdit();
}
result = dvTWR.Find(dataRowView["ID"]);
if (result != -1)
{
dvTWR[result].BeginEdit();
dvTWR[result]["Selected"] = true;
dvTWR[result].EndEdit();
}
}
dvTWR.Dispose();        // Commit/close tables
dvRWY.Dispose();

在带批注的代码行中,将触发异常:

System.Data.ReadOnlyException:"列'选定'是只读的。

谁能告诉我我的方式错误?

Dai 是正确的:数据视图无法修改静态公共内存中表。 但是,直接绑定到数据表的数据网格视图可以。

这对我来说是一个更好的解决方案,因为最终我需要显示"选定"行:我为每个表创建了一个 datagridview,并将每个表放在选项卡控件容器中。我在设计器中选中了每个数据网格视图的"可以编辑"框。

然后可以向下钻取以在设计器中修改每列的只读属性,但我发现在将数据从文本文件读入数据表后分配只读属性更容易(任何一个都可以工作,并且可以通过编程方式更改设计器设置,因为它们实际上是相同的属性)。

循环"选定"列行 true 或 false 可以方便地依赖于应用于 datagridview 的过滤器,从而使单个调用例程高效(只需对 datagridview 应用或不应用过滤器,并将 dgv 和/或列传递给被调用的例程)。

另外,用户可以取消/选中"选定"行。底层表已更改!然后,可以有效地在"选定"上过滤表以查找其他事件/输出。

// schema built in VS designer...
static public DataTable APT = new SCTData.APTDataTable();
// Table populated from FAA fixed-column text files (cols vary by file)
ReadFixes.FillAPT();
// Assign the table to the datagridview, apply filter and sort
DgvArpt.DataSource = APT;
(DgvArpt.DataSource as DataTable).DefaultView.RowFilter = filter;
AdjustColumnOrderNSort(DgvArpt);
// Loop the filtered datagrid to make "Selected" col = true
UpdateSelected(DgvArpt,true);
private void UpdateSelected (DataGridView dgv, bool hasFilter = false)
{
// If the filter is applied, selected boxes are true
// otherwise, ALL the selected boxes are false
// But if the ShowAll box is checked, ignore the update
if (chkboxShowAll.Checked == false)
{
foreach (DataGridViewRow row in dgv.Rows)
{
row.Cells["Selected"].Value = hasFilter;
}
}
}

最新更新