2013-12-07 86 views
0

當我從DropDownList中選擇任何值時,第一個被選中。DropDownList值不會改變

代碼的用途是每當我從DropDownList中選擇一個值時,數據庫中相應的值應顯示在TextBox中。

protected void Page_Load(object sender, EventArgs e) 
    { 
     SqlConnection con = new SqlConnection("connection string"); 
     con.Open(); 
     DataTable Seminars = new DataTable(); 
     SqlDataAdapter adapter = new SqlDataAdapter("SELECT SeminarName, ID FROM SeminarData", con); 
     adapter.Fill(Seminars); 
     DropDownList1.DataSource = Seminars; 
     DropDownList1.DataTextField = "SeminarName"; 
     DropDownList1.DataValueField = "SeminarName"; 
     DropDownList1.DataBind(); 
     con.Close(); 

    } 

protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e) 
{ 
    SqlConnection con = new SqlConnection("connection string"); 
    con.Open(); 
    DataTable dt = new DataTable(); 
    SqlCommand sqlCmd = new SqlCommand("SELECT SeminarNameE,TrainerName FROM SeminarData WHERE SeminarName='" + DropDownList1.SelectedItem.Value +"'", con); 
    SqlDataAdapter sqlDa = new SqlDataAdapter(sqlCmd); 
    sqlDa.Fill(dt); 

    if (dt.Rows.Count > 0) 
    { 
     TextBox1.Text = dt.Rows[0]["SeminarNameE"].ToString(); 
     TextBox2.Text = dt.Rows[0]["TrainerName"].ToString(); 
    } 



} 

回答

1

這個替換您的頁面加載:

protected void Page_Load(object sender, EventArgs e) 
{ 
    if (!Page.IsPostBack) { 
    SqlConnection con = new SqlConnection("connection string"); 
    con.Open(); 
    DataTable Seminars = new DataTable(); 
    SqlDataAdapter adapter = new SqlDataAdapter("SELECT SeminarName, ID FROM SeminarData", con); 
    adapter.Fill(Seminars); 
    DropDownList1.DataSource = Seminars; 
    DropDownList1.DataTextField = "SeminarName"; 
    DropDownList1.DataValueField = "SeminarName"; 
    DropDownList1.DataBind(); 
    con.Close(); 
    } 
} 

它需要Page.IsPostBack,因爲每次你綁定,你清楚的任何選擇!在此代碼中,它綁定在每個頁面加載上。添加!Page.IsPostback將確保它僅綁定第一個負載。