简体   繁体   English

无法将值从下拉列表选定的值传递给 SQL WHERE 子句

[英]Unable to pass value to SQL WHERE clause from dropdownlist selected value

I am trying to pass value from dropdown list to sql query WHERE clause but it is failing and not returning any value but when i give the value directly in WHERE it is working fine only problem is from addwithvalue command it is not passing the value.我试图将值从下拉列表传递到 sql 查询 WHERE 子句,但它失败并且没有返回任何值,但是当我直接在 WHERE 中给出值时,它工作正常,唯一的问题是来自 addwithvalue 命令,它没有传递值。 When i run this it is showing as there is no value at position 0 in line ' string champ = dt.Rows[0]["mc"].ToString();当我运行它时,它显示为在 ' string champ = dt.Rows[0]["mc"].ToString(); 行中的位置 0 处没有值。 ' Please check and help, '请检查并帮助,

            string query = "SELECT mc, tower, image from datatable WHERE month= '@month' AND mc IS NOT NULL AND image IS NOT NULL";
            SqlCommand cmd = new SqlCommand(query, con);
            cmd.Parameters.AddWithValue("@month", ChampMonth.SelectedValue);
            SqlDataAdapter sda = new SqlDataAdapter(cmd);
            cmd.ExecuteScalar();
            DataTable dt = new DataTable();
            sda.Fill(dt);
            string champ = dt.Rows[0]["mc"].ToString();
            string tower = dt.Rows[0]["tower"].ToString();
            string img = dt.Rows[0]["image"].ToString();
            Label1.Text = champ;
            Label2.Text = tower;
            img = Server.MapPath(img);
            Image1.ImageUrl = img;
        }

You code can look like this:您的代码可能如下所示:

        string query = "SELECT mc, tower, image from datatable WHERE month = @month " +
                       "AND mc IS NOT NULL AND image IS NOT NULL";

        using (SqlCommand cmd = new SqlCommand(query, con))
        {
            cmd.Connection.Open();

            cmd.Parameters.Add("@month", SqlDbType.NVarChar).Value = ChampMonth.SelectedValue;

            DataTable dt = new DataTable();
            dt.Load(cmd.ExecuteReader());

            if (dt.Rows.Count > 0) {
                Label1.Text = dt.Rows[0]["mc"].ToString();
                Label2.Text = dt.Rows[0]["tower"].ToString();
                string img = Server.MapPath(dt.Rows[0]["image"].ToString());
                Image1.ImageUrl = img;
            }
        }

a few things:一些东西:

The sql command object has a connection object - no need to create one
The sql command object has a reader built in - no need to create one
The sql command object has a command text.

You ONLY ever need a data adaptor if you going to update your data table object in code.如果您要在代码中更新您的数据表对象,您只需要一个数据适配器。

And you don't show how/when you created your connection object.并且您没有显示创建连接对象的方式/时间。

You should post the markup that drives the dropdownlist (combo box), since it not clear if it returns 1-12, or actual text - that part might still be wrong.您应该发布驱动下拉列表(组合框)的标记,因为不清楚它是否返回 1-12 或实际文本 - 该部分可能仍然是错误的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM