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.
Hi..CAN Lu
ReplyDeleteThank You
Its very useful for me....
Simply Brilliant! Thanks a ton!
ReplyDeletemade my job easy... great :-)
ReplyDeleteHello Can,
ReplyDeleteyour 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
Display and hide rows in DataGridView in C#.NET
ReplyDeleteThank You So Much
ReplyDelete