2013-12-07 5 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은 첫 번째로드 만 바인딩하도록합니다.

관련 문제