You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C#技术问题:如何通过DropDownList从SQL数据库填充两个网页文本框

How to Populate TextBoxes from SQL Using DropDownList Selection in C#

Let's walk through how to get your two text boxes filled when a user selects an item from your DropDownList. You already have the DropDownList configured with AutoPostBack and an event handler, so we'll build on that.


Step 1: Add the TextBox Controls to Your ASPX Page

First, add two TextBox elements to your default.aspx where you want the data to appear. I recommend setting them to read-only since they're populated from the database:

<!-- Place these wherever you want the text boxes on your page -->
<asp:TextBox ID="txtPlayerDetail1" runat="server" ReadOnly="true" CssClass="form-control"></asp:TextBox>
<asp:TextBox ID="txtPlayerDetail2" runat="server" ReadOnly="true" CssClass="form-control"></asp:TextBox>

Step 2: Implement the Event Handler in Code-Behind

Open default.aspx.cs and write the logic for the DropDownList1_SelectedIndexChanged method. We'll use ADO.NET to safely query the database and populate the text boxes.

First, make sure you have the required using directive at the top:

using System.Data.SqlClient;

Then, the event handler code:

protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
    // Clear text boxes if no valid selection is made
    txtPlayerDetail1.Text = string.Empty;
    txtPlayerDetail2.Text = string.Empty;

    // Skip if the default "Please Select" item is chosen
    if (string.IsNullOrEmpty(DropDownList1.SelectedValue))
        return;

    // Replace with your actual connection string (copy from your SqlDataSource1 if needed)
    string connString = "Your_SQL_Connection_String";
    
    // Replace with your table name and the columns you want to fetch
    string query = "SELECT PlayerAge, PlayerPosition FROM Players WHERE ID = @PlayerID";

    // Use using statements to auto-dispose database resources
    using (SqlConnection conn = new SqlConnection(connString))
    using (SqlCommand cmd = new SqlCommand(query, conn))
    {
        // Add parameter to prevent SQL injection (critical for security)
        cmd.Parameters.AddWithValue("@PlayerID", DropDownList1.SelectedValue);

        conn.Open();
        SqlDataReader reader = cmd.ExecuteReader();

        // If a matching record is found, populate the text boxes
        if (reader.Read())
        {
            txtPlayerDetail1.Text = reader["PlayerAge"].ToString();
            txtPlayerDetail2.Text = reader["PlayerPosition"].ToString();
        }

        reader.Close();
    }
}

Key Replacements You Need to Make

  • Your_SQL_Connection_String: Grab this from your existing SqlDataSource1 configuration (look for the ConnectionString attribute) or your web.config file.
  • Players: Replace with your actual database table name.
  • PlayerAge and PlayerPosition: Swap these with the column names from your table that you want to display in the text boxes.

Alternative: Declarative Binding with SqlDataSource

If you prefer to avoid writing manual ADO.NET code, you can use a second SqlDataSource to bind directly to the text boxes:

  1. Add the second data source to default.aspx:
<asp:SqlDataSource ID="SqlDataSource2" runat="server"
    ConnectionString="Your_SQL_Connection_String"
    SelectCommand="SELECT PlayerAge, PlayerPosition FROM Players WHERE ID = @PlayerID">
    <SelectParameters>
        <asp:ControlParameter Name="PlayerID" ControlID="DropDownList1" PropertyName="SelectedValue" />
    </SelectParameters>
</asp:SqlDataSource>
  1. Update your text boxes to use data binding expressions:
<asp:TextBox ID="txtPlayerDetail1" runat="server" ReadOnly="true" 
    Text='<%# Eval("PlayerAge") %>'></asp:TextBox>
<asp:TextBox ID="txtPlayerDetail2" runat="server" ReadOnly="true" 
    Text='<%# Eval("PlayerPosition") %>'></asp:TextBox>
  1. Modify the event handler to trigger data binding:
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
    if (!string.IsNullOrEmpty(DropDownList1.SelectedValue))
    {
        // Refresh data binding for the page
        Page.DataBind();
    }
    else
    {
        txtPlayerDetail1.Text = string.Empty;
        txtPlayerDetail2.Text = string.Empty;
    }
}

This approach is simpler for basic scenarios, while the ADO.NET method gives you more control over error handling and data manipulation.

内容的提问来源于stack exchange,提问作者Tony

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 09:01:00