萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> ASP.NET 程式設計

ASP.NET 資料繫結實戰:GridView、DropDownList、RadioButtonList、CheckBoxList 兩級聯動

完整後端程式碼

public partial class _Default : Page
{
    protected string Title = "大家好"; // 供前端 <%# Title %> 使用

    protected void Page_Load(object sender, EventArgs e)
    {
        string connStr = ConfigurationManager.ConnectionStrings["strsql"].ConnectionString;

        using (SqlConnection conn = new SqlConnection(connStr))
        using (SqlCommand cmd = conn.CreateCommand())
        {
            cmd.CommandText = "SELECT * FROM List";
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            DataSet ds = new DataSet();
            da.Fill(ds);

            // 繫結 RadioButtonList & CheckBoxList
            BindListControl(RadioButtonList1, ds.Tables[0], "listname", "id");
            BindListControl(CheckBoxList1, ds.Tables[0], "listname", "id");
        }

        if (!IsPostBack)
        {
            BindProvinces(connStr);
        }
    }

    private void BindListControl(ListControl ctrl, DataTable dt, string textField, string valueField)
    {
        ctrl.DataSource = dt;
        ctrl.DataTextField = textField;
        ctrl.DataValueField = valueField;
        ctrl.DataBind();
    }

    private void BindProvinces(string connStr)
    {
        using (SqlConnection conn = new SqlConnection(connStr))
        using (SqlCommand cmd = conn.CreateCommand())
        {
            cmd.CommandText = "SELECT provinceid, provincename FROM Province";
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            DataTable dt = new DataTable();
            da.Fill(dt);
            BindListControl(DropDownList1, dt, "provincename", "provinceid");
        }
    }

    protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
    {
        string connStr = ConfigurationManager.ConnectionStrings["strsql"].ConnectionString;
        using (SqlConnection conn = new SqlConnection(connStr))
        using (SqlCommand cmd = conn.CreateCommand())
        {
            cmd.CommandText = "SELECT cityid, cityname FROM City WHERE provinceid = @pid";
            cmd.Parameters.AddWithValue("@pid", DropDownList1.SelectedValue);
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            DataTable dt = new DataTable();
            da.Fill(dt);
            BindListControl(DropDownList2, dt, "cityname", "cityid");
        }
    }
}

前端重點

  • DropDownList1 設定 AutoPostBack="true" 並綁定 OnSelectedIndexChanged。
  • 使用 <%# Title %> 需呼叫 Page.DataBind() 或控制項層級 DataBind()。
  • 參數化查詢防止 SQL Injection。

優化建議

  1. 將資料存取層抽離為 Repository/Service,避免在 Code-Behind 寫 SQL。
  2. 使用 ObjectDataSource 或 Model Binding (ASP.NET 4.5+) 簡化繫結宣告。
  3. 省市資料量大時,考慮快取 Province 與 City 表至 Application/Redis。
  4. 前端改用 AJAX (jQuery/Fetch) 呼叫 WebMethod/Web API 取得城市清單,避免整頁 PostBack。
copyright © 萬盛學電腦網 all rights reserved