2013-12-07 87 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将确保它仅绑定第一个负载。