ASP.net DropDownList資料繫結及使用詳解
1. dropdownlist 繫結資料
1.1 固定繫結(適合已經固定的資料繫結到dropdownlist)
例項:
<asp:DropDownList runat="server"ID="ddlArea" Width="120px" >
<asp:Listitem value="0">選擇性別</asp:Listitem>
<asp:Listitem value="1">男</asp:Listitem>
<asp:Listitem value="2">女</asp:Listitem>
</asp:DropDownList>
1.2 動態繫結:(每次繫結都要清除一下原來的記錄,例:ddlArea.Items.Clear();)
例項:
SqlConnectionconn = new SqlConnection("server=.;uid=sa;database=pubs");
SqlDataAdapter dap = new SqlDataAdapter("select * from job", conn);
DataTable dt = new DataTable();
dap.Fill(dt);
DropDownList1.Items.Clear();
DropDownList1.DataSource = dt;
DropDownList1.DataTextField = "job_desc";
DropDownList1.DataValueField = "job_id";
DropDownList1.DataBind();
DropDownList1.Items.Insert(0, new ListItem("選擇", "繫結資料"));
或者:
SqlConnection conn = newSqlConnection("server=.;uid=sa;database=pubs");
SqlDataAdapter dap = new SqlDataAdapter("select * from job", conn);
DataTable dt = new DataTable();
dap.Fill(dt);
if (dt.Rows.Count != 0)
{
DropDownList1.Items.Clear();
for (int i = 0; i < dt.Rows.Count; i++)
{
DropDownList1.Items.Add(new ListItem(
dt.Rows[i]["顯示值"].ToString(),
dt.Rows[i]["usbkey"].ToString()));
}
DropDownList1.Items.Insert(0, "選擇");
DropDownList1.Items[0].Value = "0"; 或
// DropDownList1.Items.Insert(0, new ListItem("選擇資料","繫結資料"));
}
else
{
DropDownList1.Items.Insert(0, "無記錄");
DropDownList1.Items[0].Value = "0";
}
2:DropDownList1的取值問題:
2.1 取DropDownList1的索引值,也就是選擇value 值<asp:Listitem value="1">男</asp:Listitem> 取1
.net中 DropDownList1.SelectedValue.ToString()
javascirpt var ddl1=document.getElementByIdx_x("DropDownList1").selectedIndex;
2.2 取DropDownList1的選項,也就是選擇item值<asp:Listitem value="1">男</asp:Listitem>取 男
.net 中DropDownList1.SelectedItem.ToString();
javascriptdocument.getElementByIdx_x("DropDownList1").options[document.getElement("selectID").selectedIndex].value
3:DropDownList1事件問題:
使用OnTextChanged,OnSelectedIndexChanged事件時,
例項:
<asp:DropDownListrunat="server"OnTextChanged="DropDownList1_TextChanged"OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged1">
OnSelectedIndexChanged這個事件要比OnTextChanged執行的早,也就是如果這兩個事件都存在,會首先執行OnSelectedIndexChanged這個事件,然後才執OnTextChanged.