在GridView中获取值显示后,当我再次单击时,DropDownList将包含重复的项目。
public void Page_Load(object sender, EventArgs e)
{
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(object sender, EventArgs e)
{
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();
}
答案 0 :(得分:0)
每次发生回发时(例如,当您单击ASP.NET按钮控件时)都会调用Page_Load
方法。数据已在第一次加载时添加并存储在ViewState中。在第二个请求中,它再次添加它。您可以使用Page.IsPostBack属性检测是否处于回发中。
public void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
// add items to drop down list
}
}
附注,确保正确处理实现IDisposable接口的所有对象。您需要确保在完成这些操作后处理它们以避免难以诊断错误。您可以在.Dispose()
块中为它们调用finally
,也可以将它们包装在using
语句中。您的SqlCommand
,SqlConnection
(这不应该是属性/字段)and
SqlDataReader all implement
IDisposable`。
答案 1 :(得分:0)
你应该把它写成:
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();
}
答案 2 :(得分:-1)
最好猜测,如果没有可编译的代码,看起来你的下拉列表会在页面加载之间保持不变,这意味着它永远不会脱离上下文(对象保留在内存中)。因此,每次页面加载时都会反复添加。您可能想要检查现有值:
public void Page_Load()
{
string sql = "select distinct cproject from I.dd.project";
con.Open();
using(SqlCommand cmd = new SqlCommand(sql, con)) {
using(SqlDataReader dr = cmd.ExecuteReader()) {
while (dr.Read())
{
//Have not tested the if statement... may need to correct it.
if(!DropDownList1.Items.Contains(dr[0].ToString())) {
DropDownList1.Items.Add(dr[0].ToString());
}
}
}
}
con.Close();
}
答案 3 :(得分:-1)
我刚刚找到了解决方案。将if(!Ispostback)放在页面加载语句中。