我有一张Customer表 - > CustomerNumber
和CustomerName
列
我有一张销售表 - > CustomerName
列
我有Label
(代表CustomerNumber)和DropDownList
(代表客户名称)
我到达DropDownList
销售表 - >客户名称为SqlDataSource
。
我想自动(使用AutoPostBack)用CustomerNumber填充Label,CustomerName在DropDownList中选择了CustomerName
示例SQL:
选择A.CustomerNumber 来自客户A,销售B. 其中B.CustomerName = DropDownList1.SelectedItems.Value
我在想这个。
我该怎么做?
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
}
答案 0 :(得分:3)
试试这个
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
if(-1 != DropDownList1.SelectedIndex)
{
using(SqlConnection connection = new SqlConnection("connectionString"))
{
connection.Open();
using(SqlCommand command = new SqlCommand("SELECT A.CUSTOMERNUMBER FROM CUSTOMER A, SALES B WHERE B.CUSTOMERNAME = @CustomerName"))
{
command.Connection = connection;
command.Parameters.AddWithValue("@CustomerName", DropDownlist1.SelectedValue.ToString());
this.Label1.Text = command.ExecuteScalar().ToString();
}
}
}
}
希望它有效。 免责声明:我没有测试代码
答案 1 :(得分:2)
protected void DropDownList1_SelectedIndexChanged(object sender,EventArgs e)
{
string selectedName = DropDownList1.SelectedValue;
string sqlQuery = "select A.CustomerNumber from Customer A, Sales B where B.CustomerName = '" + DropDownList1.SelectedValue + "'";
// pass you sql query to command object and call execute scalar method
label1.Text = dbCommand.ExecuteScalar().ToString();
}
ExecuteScalar做了什么?