将下拉列表值绑定到文本框

时间:2013-07-01 19:00:34

标签: asp.net

当用户选择订单ID时,其余订单信息将显示在标签中。显示以下内容:员工ID,订单日期,运费,发货名称和国家/地区。应该以编程方式使用直接数据访问来实现此功能。

编辑:代码示例和其他说明。

String CS = onfigurationManager.ConnectionStrings["NORTHWNDConnectionString"].ConnectionStr‌​ing; 
using (SqlConnection con = new SqlConnection(CS)) 
{ 
    SqlCommand cmd = new SqlCommand("SELECT OrderID FROM Orders", con);
    con.Open();
    DropDownList1.DataSource = cmd.ExecuteReader();
    DropDownList1.DataTextField = "OrderID";
    DropDownList1.DataValueField = "OrderID";
    DropDownList1.DataBind();
    Label1.Text = Convert.ToString(DropDownList1.SelectedItem.Text); 
} 

我想要的是在下拉列表中选择值时显示的订单表中的其他字段。

2 个答案:

答案 0 :(得分:0)

您可以从SQL查询结果中创建数据表,然后从ID列向下拉列表中添加项目。然后,当您从DDL中选择一个项目时,将显示数据表中的行与所选订单ID匹配的信息。

我可以编写代码,如果你不想清除我的意思。

更新:使用代码

var ds = new DataSet();

using (var conn = new SqlConnection(connection))
{
    conn.Open();
    var command = new SqlCommand("Your SQL Query", conn);
    var adapter = new SqlDataAdapter(command);
    adapter.Fill(ds);
    conn.Close();
 } //Now you have a dataset, with one table that matches your query result.

//And now we can use a foreach loop to add every OrderID to dropdownlis

 foreach (DataTable table in ds.Tables)
 {
     foreach (DataRow dr in table.Rows)
     {
         DDLname.Items.Add(dr[0].ToString());
     }
 }

//onSelectedValue event
string orderID = DDLname.Text.toString();
Label1.Text = orderID;
foreach (DataTable table in ds.Tables)
{
    foreach (DataRow dr in table.Rows)
    {
        if(dr[0].toString().equals(orderID))
        {
            Label2.text = dr[1].toString();
            Label3.text = dr[2].toString();
            etc....
        }
    }
}

答案 1 :(得分:0)

当您使用ASP.Net标记您的问题时,我认为这是ASP.Net Webforms应用程序的一部分。这意味着下拉列表将位于浏览器的网页内。我不清楚您是否希望在用户选择项目时立即显示标签,或者仅在向服务器发布帖子后显示标签。 在第一种情况下,您需要使用javascript和Ajax或JSON之类的东西来获取要为所选项目显示的数据。在第二种情况下,您可以为下拉列表的SelectedIndex_Changed事件添加事件处理程序。这个处理程序应该这样做:

    string CS = ConfigurationManager.ConnectionStrings["NORTHWNDConnectionString"].ConnectionString;
    using (SqlConnection con = new SqlConnection(CS))
    {
        SqlCommand cmd = new SqlCommand("SELECT OrderID FROM Orders WHERE OrderId = @OrderId", con);
        cmd.Parameters.AddWithValue("@OrderId", DropDownList1.SelectedItem.Value);
        con.Open();
        if (reader.Read())
        {
            SqlDataReader reader = cmd.ExecuteReader();
            Label1.Text = String.Format("Employee ID: {0}, order date: {1}, freight: {2}, shipped name: {3}, and country {4}."
                , reader["employeeid"].ToString()
                , reader["orderdate"].ToString()
                , reader["freight"].ToString()
                , reader["shipname"].ToString()
                , reader["shipcountry"].ToString());
        }
    }
相关问题