C# 如何隐藏DataGridVew行
在C#WinForms项目中,我将DataGridView的数据源作为DataTable进行迭代,并对源数据库进行检查,确定其中一列中的值是否有效。如果它是一个有效值,我想隐藏它,这样我只会以DGV显示具有无效值的行结束 这是我目前掌握的psuedo代码C# 如何隐藏DataGridVew行,c#,winforms,datagridview,datatable,C#,Winforms,Datagridview,Datatable,在C#WinForms项目中,我将DataGridView的数据源作为DataTable进行迭代,并对源数据库进行检查,确定其中一列中的值是否有效。如果它是一个有效值,我想隐藏它,这样我只会以DGV显示具有无效值的行结束 这是我目前掌握的psuedo代码 private void btnValidate_Click(object sender, EventArgs e) { DataTable dt = ((DataTable)dgvMyDataGridView.DataSour
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
*/
}
}
}
但当我运行时,我会出现以下错误:
System.InvalidOperationException: 'Row associated with the currency manager's position cannot be made invisible.'
我不能只执行类似于drValidationRow.Visible=false的操作,因为它没有Visible
属性,我猜这是因为该行来自数据表,而不是DGV
我如何做到这一点?您不需要计数器。如果Rows.Count=0,您只需刷新dgv即可。AFAIK您可以使用SuspendBinding
,将Visible
设置为false,并使用ResumeBinding
afterwards。但不确定。您可以将bool
(隐藏)列添加到数据表中。验证通过/失败时,将此列的值设置为true/false,然后只需使用dt.DefaultView.RowFilter=“[MyBoolColumn]=false”
。需要时反转,设置.RowFilter=string.Empty
以移除过滤器。当过滤器处于活动状态时,更改bool列的值将立即更新视图(无需执行任何其他操作)。Shawn是对的,请查看:@Shawn,我检查了JSL提供的链接,该链接起了作用,但我遇到了一种情况,即由于所有值均有效,因此没有显示行,它隐藏了DGV中的所有行。我的想法是添加一个计数器,将隐藏的行数与DGV中的行数进行比较,如果所有行都有效,则只刷新DGV。“有没有更好的办法来处理这种情况呢?”马基,我真的不知道你想达到什么目的。如果所有值都有效,则将没有任何内容可显示。对的
System.InvalidOperationException: 'Row associated with the currency manager's position cannot be made invisible.'