[英]dropdownlist Select from SQL database
我正在嘗試做一個汽車維修項目,但有一個小問題。 該項目是這樣的:
針對不同汽車的4種維護計划。
CarA ( MirrorA, etc etc )
CarB ( MirrorB, etc etc )
CarC ( MirrorC, etc etc )
CarD ( MirrorD, etc etc )
我要做的是,當我從DropDownList
選擇一輛Car
時,程序會為汽車選擇正確的維護計划!
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();
現在我被卡住了。
現在您需要在此列表中設置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; }
...
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.