如何按c#中的单元格值过滤datagridview中的行

时间:2017-10-04 16:30:53

标签: c# datagridview filter

我有一个包含5个单元格的数据格式视图 我想在某些条件下过滤行,这是第5个Cell值isn< t 0 0

我尝试了以下代码,但它没有正常工作

 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;

            }
        }

我用于接收数据的存储过程

    @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 +'%'

1 个答案:

答案 0 :(得分:2)

尝试以下代码并查看评论以获取详细信息。

            //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;
                }
            }