我想检查第一列是否包含textbox1并在列表视图中显示整行

本文关键字:列表 textbox1 视图 显示 包含 是否 检查 一列 | 更新日期: 2023-09-27 18:29:58

我是C#的新手,所以如果答案很明显,请原谅我。如果C.CompanyName在textBox1中包含给定的文本,我想连接到我的SQL Server Management Studio并在listview中显示项。可能有一个错误,但我找不到。非常感谢您的帮助。

SqlConnection cnn = new SqlConnection("Initial Catalog=Northwind;Data Source=localhost;Integrated Security=SSPI;");
private void button1_Click(object sender, EventArgs e)
{
    cnn.Open();
    SqlCommand cmd = new SqlCommand("SELECT c.CompanyName, o.Freight FROM Customers c INNER JOIN Orders o ON c.CustomerID = o.CustomerID WHERE c.CompanyName LIKE %@recherche%", cnn);
    cmd.Parameters.AddWithValue("@recherche", textBox1.Text);
    SqlDataReader dr = cmd.ExecuteReader();
    if (dr.HasRows)
    {
        while (dr.Read())
        {
            string companyname = dr.GetString(0);
            string salary = dr.GetDecimal(1).ToString();
            ListViewItem rowadd = listView1.Items.Add(companyname);
            rowadd.SubItems.Add(salary);
        }
    }
    cnn.Close();
}

我想检查第一列是否包含textbox1并在列表视图中显示整行

试试这个:

SqlCommand cmd = new SqlCommand("SELECT c.CompanyName, o.Freight FROM Customers c INNER JOIN Orders o ON c.CustomerID = o.CustomerID WHERE c.CompanyName LIKE @recherche", cnn);
cmd.Parameters.AddWithValue("@recherche", "%" + textBox1.Text + "%");

将您的命令更改为:

SqlCommand cmd = new SqlCommand("
    SELECT c.CompanyName, o.Freight
    FROM Customers c
        INNER JOIN Orders o ON c.CustomerID = o.CustomerID
    WHERE c.CompanyName LIKE '%' + @recherche + '%'
", cnn);