Reputation: 89
I have a datagridview in a form that has 5 cells i want to filter rows in some condition which is the 5th Cell value isn't 0
I tried the following code but it didn't work correctly
for (int i = 0; i < frm.dataGridView1.Rows.Count; i++)
{
if (frm.dataGridView1.Rows[i].Cells[5].Value.ToString() == "0")
{
CurrencyManager currencyManager1 = (CurrencyManager)dataGridView1.BindingContext[dataGridView1.DataSource];
currencyManager1.SuspendBinding();
dataGridView1.Rows[i].Selected = false;
dataGridView1.Rows[i].Visible = false;
currencyManager1.ResumeBinding();
}
else
{
dataGridView1.Rows[i].Visible = true;
dataGridView1.Rows[i].Selected = true;
}
}
The stored procedure i use for receiving data
@Criterion varchar(30)
as
SELECT [id] as
,[car_num]
,[customer]
,[driver]
,[first]
,[second]
,[sum]
,[price]
,[date1]
,[date2]
,[city]
,[type]
FROM [dbo].[Data]
where
[car_num]+
[customer]+
[driver]+
convert (varchar, [first])+
convert (varchar, [second])+
convert (varchar, [sum])+
convert (varchar, [price])
like '%' + @Criterion +'%'
Upvotes: 0
Views: 2551
Reputation: 12751
Try below code and look into comments for details.
//USE A FOREACH, YOU DO NOT NEED WORRY ABOUT INDEXS (WHICH CAUSES PROBLEMS MANY TIMES)
foreach (DataGridViewRow rowItem in dataGridView1.Rows)
{
//CHECK FOR OBJECT EXISTENCE BEFORE DOING ANYTHING
//AVOID ACCESSING CELL VALUE WITH INDEX. GO WITH COLUMN NAME. NO ISSUES IF COLUMNS ARE ALTERED LATER POINT.
if (rowItem.Cells["number"].Value != null)
{
//CHECK THE VALUE AND SET VISISBLE/INVISIBLE
if (rowItem.Cells["number"].Value.ToString() == "0")
rowItem.Visible = false;
else
rowItem.Visible = true;
}
}
Upvotes: 3