dropdownlist从SQL数据库中选择

时间:2015-03-31 17:08:16

标签: c# asp.net sql-server

我正在尝试做一个汽车维修项目,我遇到了一个小问题。该项目类似于:

针对不同车型的4种维修计划。

 CarA ( MirrorA, etc etc )
 CarB ( MirrorB, etc etc )
 CarC ( MirrorC, etc etc )
 CarD ( MirrorD, etc etc )

我想要做的是当我选择Car(来自DropDownList)时,程序会为汽车选择正确的维护计划!

SqlCommand cmd = new SqlCommand("Select id, description from accauto_maps", con);
con.Open();
DropDownList1.DataSource = cmd.ExecuteReader();
DropDownList1.DataTextField = "description";
DropDownList1.DataValueField = "id";
DropDownList1.DataBind(); 

现在我被卡住了。

1 个答案:

答案 0 :(得分:0)

现在您需要在此列表中设置SelectedValue 和/或 定义事件OnSelectedIndexChanged,您将在其中处理用户的选择

在示例下面我们是如何做到的:

<asp:DropDownList ID="ddlStatus" AutoPostBack="True" runat="server" DataSourceID="EDSLookStatus"
    DataValueField="cd" 
    DataTextField="lookupName" 
    OnSelectedIndexChanged="ddlStatus_SelectedIndexChanged" />
<asp:TextBox ID="txtBxStatus" runat="server" Text='<%# Bind("status") %>' Visible="False" />

这是诀窍:添加了隐藏文本框,链接到“状态”。当ddl更改值时,它会为此txtBx设置新值:

protected void ddlStatus_SelectedIndexChanged(object sender, EventArgs e)
{
    DropDownList ddl = FormViewClient.FindControl("ddlStatus") as DropDownList;
    TextBox txtBx = FormViewClient.FindControl("txtBxStatus") as TextBox;
    if (ddl != null && txtBx != null)
    { txtBx.Text = ddl.SelectedValue; }
}

设置选定值:

<asp:FormView ... OnDataBound="FormViewClient_DataBound" >

protected void FormViewClient_DataBound(object sender, EventArgs e)
{
    ...
    DropDownList ddl = FormViewClient.FindControl("ddlStatus") as DropDownList;
    TextBox txtBx = FormViewClient.FindControl("txtBxStatus") as TextBox;
    if (ddl != null && txtBx != null)
    { ddl.SelectedValue = txtBx.Text; }
    ...
}