如何更新文本框的 onTextChange 事件上的下拉列表

本文关键字:onTextChange 事件 下拉列表 文本 何更新 更新 | 更新日期: 2023-09-27 18:30:23

我有一个名为txtDatetextBox

   <asp:TextBox ID="txtDate" runat="server" AutoPostBack="true" Width="120px" 
    ontextchanged="txtDate_TextChanged" ></asp:TextBox>

我还有一只叫DropDownList1dropDownList

    <asp:DropDownList ID="DropDownList1" runat="server" 
                DataSourceID="SqlDataSource2" DataTextField="sTime" DataValueField="sTime" 
                AutoPostBack="True">
    </asp:DropDownList>

DropDownList正在从一个名为SqlDataSource2的sqlDataSourse获取数据。我需要更新textBox onTextChange事件的下拉列表。所以我写了这个。

    protected void txtDate_TextChanged(object sender, EventArgs e)
    {
       SqlDataSource2.SelectCommand = "NEW SQL COMMAND";
    }

但这不会更新dropDownList.如果有人可以,请帮助我。

如何更新文本框的 onTextChange 事件上的下拉列表

我找到了。我将 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代码。

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();
}