Friday 17 April 2009

How to Hide Rows from DataGridView in WinForm Application?

When you see the title, you may wonder why I am writing this, this is so obvious, we can easily achieve this by writing something like:

foreach (DataGridViewRow dgvr in MyDataGridView.Rows)
{
if (string.IsNullOrEmpty(dgvr.Cells["sales"].Value.ToString()))
{
dgvr.Visible = false;
}
}

However if you do this, you are more likely to get the error:
InvalidOperationException,
Row associated with the currency manager's position cannot be made invisible.

Why? Because you cannot make modifications to a row at runtime which is bound to a DataSource, unless you suspend the binding on all rows using CurrencyManager object like code shows below:

CurrencyManager cm = (CurrencyManager)BindingContext[dgvBulkSheetDtl.DataSource];
foreach (DataGridViewRow dgvr in MyDataGridView.Rows)
{
if (string.IsNullOrEmpty(dgvr.Cells["sales"].Value.ToString()))
{
cm.SuspendBinding();
dgvr.Visible = false;
}
}

Simple isn’t it? One thing you need to be aware is that if your DataGridView allows user to sort the columns, then you have to hide the rows again because the hidden rows will show up again. In this case, what you probably can do is to filter the data out from your data source.

6 comments:

  1. Simply Brilliant! Thanks a ton!

    ReplyDelete
  2. made my job easy... great :-)

    ReplyDelete
  3. Hello Can,

    your code is awesome, but I have a problem that I want to hide every first row of the Datagridview, I am using switch case to hide multiple datatable 1st row in datagridview to hide but attempting with 2nd datatable its show the exception of "Row associated with the currency manager's position cannot be made invisible."
    Please help me...

    My code is here

    CurrencyManager cm = null;
    cm = (CurrencyManager)BindingContext[grdKeywords.DataSource];

    switch (Value)
    {
    case "13":
    for (int i = 0; i <= grdKeywords.Rows.Count; i++)
    {
    if (grdKeywords.Rows[0].Visible == true)
    {
    cm.SuspendBinding();
    grdKeywords.Rows[0].Visible = false;
    }
    if (grdKeywords.Rows[1].Visible == true)
    {
    cm.SuspendBinding();
    grdKeywords.Rows[1].Visible = false;
    }
    }
    break;
    default:
    for (int i = 0; i <= grdKeywords.Rows.Count; i++)
    {
    if (grdKeywords.Rows[0].Visible == true)
    {
    cm.SuspendBinding();
    grdKeywords.Rows[0].Visible = false;
    }
    }
    break;
    }

    Thanks and regards,

    Nitish

    ReplyDelete