【问题标题】:How can I search more columns in DataGridView in C#如何在 C# 中的 DataGridView 中搜索更多列
【发布时间】:2021-10-26 21:52:32
【问题描述】:

我想从 DatagridView 中搜索更多列。我只能搜索产品名称,但我也想搜索品牌名称和类别名称。我怎样才能做到这一点?

这是我的代码:

 public void LoadProducts()
    {
        int i = 0;
        dataGridView1.Rows.Clear();
        cn.Open();
        cm = new SqlCommand("select p.pcode, p.barcode, p.pdesc, b.brand, c.category, p.price1, p.price2, p.qty from tblproduct as p inner join tblbrand as b on b.id = p.bid inner join tblcategory as c on c.id = p.cid where p.pdesc like '" + txtSearch.Text + "%' order by p.pdesc", cn);
        dr = cm.ExecuteReader();
        while (dr.Read())
        {
            i++;
            dataGridView1.Rows.Add(i, dr[0].ToString(), dr[1].ToString(), dr[2].ToString(), dr[3].ToString(), dr[4].ToString(), dr[5].ToString(), dr[6].ToString(), dr[7].ToString());
        }
        dr.Close();
        cn.Close();
    }

【问题讨论】:

  • 不要以这种方式构建 SQL 查询。您需要对它们进行参数化。
  • 说到SQL,你可能想刷一些入门教程。您实际上是在询问如何向 where 子句添加条件,这很简单。
  • 您可能还想研究使用 DGV 的最佳方法 - 将字符串逐行插入其中远非最佳使用方法。关键字:数据源
  • 感谢您的 cmets.... :)
  • 另外,你应该使用using来处理你的连接、命令和阅读器,你不应该缓存你的连接对象

标签: c# sql visual-studio-code datagridview datagridviewcolumn


【解决方案1】:

经过深入研究,我终于得到了解决方案:

public void LoadProducts()
    {
        int i = 0;
        dataGridView1.Rows.Clear();
        cn.Open();
        cm = new SqlCommand("select p.pcode, p.barcode, p.pdesc, b.brand, c.category, p.price1, p.price2, p.qty from tblproduct as p inner join tblbrand as b on b.id = p.bid inner join tblcategory as c on c.id = p.cid where p.pdesc like '" + txtSearch.Text + "%' or b.brand like '" + txtSearch.Text + "%' or c.category like '" + txtSearch.Text + "%' order by p.pdesc", cn);
        dr = cm.ExecuteReader();
        while(dr.Read())
        {
            i++;
            dataGridView1.Rows.Add(i, dr[0].ToString(), dr[1].ToString(), dr[2].ToString(), dr[3].ToString(), dr[4].ToString(), dr[5].ToString(), dr[6].ToString(), dr[7].ToString());
        }
        dr.Close();
        cn.Close();
    }

【讨论】:

  • 还是很糟糕。
猜你喜欢
  • 1970-01-01
  • 2011-09-06
  • 1970-01-01
  • 2012-10-21
  • 2014-12-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多