[英]How to update dropDownList on the onTextChange event of a textBox
我有一個名為txtDate
的textBox
<asp:TextBox ID="txtDate" runat="server" AutoPostBack="true" Width="120px"
ontextchanged="txtDate_TextChanged" ></asp:TextBox>
而且我還有一個名為DropDownList1
的dropDownList
<asp:DropDownList ID="DropDownList1" runat="server"
DataSourceID="SqlDataSource2" DataTextField="sTime" DataValueField="sTime"
AutoPostBack="True">
</asp:DropDownList>
DropDownList正在從名為SqlDataSource2
的sqlDataSourse中獲取數據。 我需要在更新下拉列表onTextChange
一個事件textBox
。 所以我寫了這個。
protected void txtDate_TextChanged(object sender, EventArgs e)
{
SqlDataSource2.SelectCommand = "NEW SQL COMMAND";
}
但這不會更新dropDownList
。 如果有人可以,請幫助我。
我找到了。 我將TextChanged事件的代碼更改為此。
protected void txtDate_TextChanged(object sender, EventArgs e)
{
SqlDataSource2.SelectCommand = "NEW SQL COMMAND";
DropDownList1.DataSourceID = "SqlDataSource2";
}
您需要在此處進行動態綁定。 將下拉HTML更改為此
<asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="True">
</asp:DropDownList>
protected void txtDate_TextChanged(object sender, EventArgs e)
{
/* This is not actual code but a kind of algorithm to proceed with*/
using(SqlConnection con = new SqlConection(you_conn_string))
{
using (command)
{
usin(SqlDataReader rdr = cmd.ExecuteReader())
{
var dt = new Datatable();
dt.load(rdr);
dropdownlist1.datasource = dt;
dropdownlist1.datatextfield="textfield";
dropdownlist1.datavaluefield="valuefield";
dropdownlist1.databind();
}
}
}
SqlDataSource2.SelectCommand = "NEW SQL COMMAND";
DataView testView = (DataView)SqlDataSource2.Select(DataSourceSelectArguments.Empty);
DataTable table = testView .ToTable();
DropDownList1.Datasource = table;
DropDownList1.Databind();
全局聲明前四行,因此無需一次又一次地定義。
如果使用此代碼,請從下拉列表.aspx代碼中刪除datatext,datavalue,datasourceID。
protected void txtDate_TextChanged(object sender, EventArgs e)
{
SqlConnection con = new SqlConection(you_conn_string)
SqlCommand cmd=new SqlCommand();
SqlDataAdapter da=new SqlDataAdapter();
Dateset ds=new Dataset();
cmd = new SqlCommand("procedure name to get data", con);
cmd.CommandType = CommandType.StoredProcedure;
da = new SqlDataAdapter(cmd);
da.Fill(ds);
dropdownlist1.datasource = ds;
dropdownlist1.datatextfield="textfield";
dropdownlist1.datavaluefield="valuefield";
dropdownlist1.databind();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.