c# - DropdownList 选择要标记的值

标签 c# mysql asp.net

我不断获取名称而不是价格。我想要的是在 DropdownList 上选择一个值并将其价格加载到标签上。

private void GetData()
{
    SqlConnection connection = new SqlConnection("Data Source = localhost\\SQLEXPRESS;Initial Catalog = MejOnlineManagementDB00;Integrated Security=True;");
    connection.Open();
    SqlCommand sqlCmd = new SqlCommand(@"SELECT price
                                            FROM Products3
                                            WHERE productName='" + DropDownList1.SelectedItem.Value.ToString() + "'", connection);
    SqlDataReader rdr = sqlCmd.ExecuteReader();
    while (rdr.Read())
    {
        lblPrice.Text = DropDownList1.SelectedValue.ToString();
    }
    connection.Close();
}

protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
    lblPrice.Text=DropDownList1.SelectedItem.Value.ToString();
}

上面是我的selectedIndex。

最佳答案

将您的代码更改为:

        private void GetData()
        {
            SqlConnection connection = new SqlConnection("Data Source = localhost\\SQLEXPRESS;Initial Catalog = MejOnlineManagementDB00;Integrated Security=True;");
            connection.Open();
            SqlCommand sqlCmd = new SqlCommand(@"SELECT price
                                                FROM Products3
                                                WHERE productName='" + DropDownList1.SelectedItem.Value.ToString() + "'", connection);
            SqlDataReader rdr = sqlCmd.ExecuteReader();
            if(dr.HasRows)
            {
                while (rdr.Read())
                {
                    lblPrice.Text = rdr.GetValue(0).ToString(); //  if price is  string use GetString(0))
                }
            }
            connection.Close();
        }

编辑:

 protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
    {
        GetData(); 
    }

关于c# - DropdownList 选择要标记的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35699580/

相关文章:

c# - 使用 System.Reflection 时验证异常时出错

c# - VS2022 c# 在文件保存上添加私有(private)修饰符

php - JSON 中的嵌套数组响应仅返回 Mysql 表中的最后一行

c# - 在同类之外不被认可的公共(public)结构

c# - 我可以按任何顺序将中间件应用于应用程序吗?

c# - 如何通过C#代码在KML中写入引号

c# - 返回 bool 的空传播运算符

c# - 将 fontawesome 图标添加到 asp.net 按钮

mysql - LEFT JOIN 表和右边不存在的空值

mysql - SQL 不同的问题