I have a Customer table --> CustomerNumber
and CustomerName
columns
I have a Sales table --> CustomerName
columns
I have a Label
(represent CustomerNumber) and a DropDownList
(represent CustomerName)
I getting to DropDownList
Sales table --> CustomerName with SqlDataSource
.
I want automaticly (with AutoPostBack) filling Label with CustomerNumber which CustomerName selected in DropDownList
Example SQL:
开发者_如何转开发select A.CustomerNumber from Customer A, Sales B where B.CustomerName = DropDownList1.SelectedItems.Value
I'm thinking like this.
How can i do that?
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
}
Try this
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();
}
}
}
}
Hope it works. Disclaimer : I didn't tested the code
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();
}
What do ExecuteScalar do?
精彩评论