【问题标题】:listbox1 to listbox2 looped from listbox1 using sql query? Is it possible?listbox1 到 listbox2 使用 sql 查询从 listbox1 循环?可能吗?
【发布时间】:2019-02-10 17:37:46
【问题描述】:

我在 sql server 上有一个名为 tblPrice 的表,其中包含 service 列和 price 列。我在 winforms 上有两个 listBox

用户将在listBox1 中添加项目,然后用户单击button

SQL 查询将搜索listbox1 中的所有项目,如果listbox1 包含来自列服务的值,则此服务的价格将添加到listbox2

我尝试了这些代码,但它没有将价格添加到 listbox2

for(int i = 0; i < listBServices.Items.Count; i++)
{
    SqlCommand cmd = new SqlCommand("SELECT price FROM tblPrice WHERE service = '@svc'",
                con.Connection);
    cmd.Parameters.Add("@svc", SqlDbType.Text).Value = listBServices.Items[i].ToString();
    SqlDataReader rd = cmd.ExecuteReader();

    while (rd.Read())
    {
        float price = rd.GetFloat(0);
        listBPrice.Items.Add(price.ToString());
    }
    rd.Close();
}

【问题讨论】:

  • SELECT price FROM price?
  • @Jimi 对不起,表名是 tblPrice
  • 现在看:WHERE service = '@svc'

标签: c# sql winforms


【解决方案1】:

试试

  SqlCommand cmd = new SqlCommand("SELECT price FROM tblPrice WHERE service = @svc"

而不是

  SqlCommand cmd = new SqlCommand("SELECT price FROM tblPrice WHERE service = '@svc'"
                                                                              ^    ^

【讨论】:

  • 嗨,先生尝试了您的建议,但我得到了System.Data.SqlClient.SqlException: 'The data types varchar and text are incompatible in the equal to operator.'
【解决方案2】:

对不起,这是我的参数错误。这段代码回答了我的问题。谢谢大家:)

                for (int i = 0; i < listBServices.Items.Count; i++)
                {
                    SqlCommand cmd = new SqlCommand("SELECT price FROM price WHERE service = @svc",
                                con.Connection);
                    cmd.Parameters.Add("@svc", SqlDbType.VarChar).Value = listBServices.Items[i].ToString();
                    SqlDataReader rd = cmd.ExecuteReader();

                    while (rd.Read())
                    {                    
                        listBPrice.Items.Add(rd["price"].ToString());
                    }
                    rd.Close();
                }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-10
    • 2019-12-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多