在C# WinForms项目中,我正在将DataGridView的DataSource作为DataTable进行迭代,我正在对源数据库进行检查,并确定其中一列的值是否有效。如果它 是 的有效值,我想把它隐藏起来,这样我就只能在DGV中显示无效值的行。
这是我目前所做的伪代码。
private void btnValidate_Click(object sender, EventArgs e)
{
DataTable dt = ((DataTable)dgvMyDataGridView.DataSource);
int intRowIndex;
for (intRowIndex = 0; intRowIndex <= dt.Rows.Count - 1; intRowIndex++)
{
DataRow drValidationRow = dt.Rows[intRowIndex];
string strNewValue = drValidationRow[5].ToString();
// Get the current row's db record ID as a string for the db query
int intCurrDgvRowId = int.Parse(dgvMyDataGridView[0, intRowIndex].Value.ToString());
// Determine if we need to show or hide the DGV's row
bool bNewValueIsValid = <db check for valid strNewValue>
if (bNewValueIsValid)
{
/*
* Hide the DGV row corresponding to the DT row ID
*/
}
}
}
我尝试了在我看来最合理的方法。
dgvmyDataGridView.Rows[intRowIndex].Visible = false;
但当我运行时,我得到了这个错误。
System.InvalidOperationException: 'Row associated with the currency manager's position cannot be made invisible.'
我不能只做一些像 drValidationRow.Visible = false
,因为没有 Visible
属性,我猜测是因为该行来自DataTable而非DGV。
我如何实现这个目标?
你不需要一个计数器。你可以直接刷新dgv,如果Rows.Count = 0 ?