Y.C Y.C - 2 months ago 17
ASP.NET (C#) Question

Asp .net dropdownlist data keep load

After I get the value show in gridview. The dropdownlist will come out duplicate value when i click again.

public void Page_Load
{
string sql = "select distinct cproject from I.dd.project";
con.Open();
SqlCommand cmd = new SqlCommand(sql, con);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
DropDownList1.Items.Add(dr[0].ToString());
}
con.Close();


}

public void button_click
{
sqldataadapter da = new sqldataadapter(Select * from lalala where id = '"+dropdownlist.item.selectedvalue.tostring()+"')
+"where A.cproject ='"+DropDownList1.SelectedValue.ToString()+"', con);
DataSet ds = new DataSet();
sda.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
}

Answer

You should write it as:

public void Page_Load
{
  if (!IsPostBack){
    string sql = "select distinct cproject from I.dd.project";
    con.Open();
    SqlCommand cmd = new SqlCommand(sql, con);
    SqlDataReader dr = cmd.ExecuteReader();
    while (dr.Read())
    {
     DropDownList1.Items.Add(dr[0].ToString());
    }
    con.Close();
  }
}

public void button_click
{
    sqldataadapter da = new sqldataadapter(Select * from lalala where id =    '"+dropdownlist.item.selectedvalue.tostring()+"')
   +"where A.cproject ='"+DropDownList1.SelectedValue.ToString()+"', con);
    DataSet ds = new DataSet();
    sda.Fill(ds);
    GridView1.DataSource = ds;
    GridView1.DataBind();
}
Comments