protected void Page_Load(object sender, EventArgs e)
{
。
。
。
。 DropDownList1.DataBind();
ListItem item = new ListItem("", "");
DropDownList1.Items.Insert(0, item); }
protected void Button1_Click(object sender, EventArgs e)
{
string sql = "select * from t_Contract where 1=1";
if (DropDownList1.Text != "")
sql += " and 合同类型='" + DropDownList1.SelectedValue + "'";
Response.Write(sql);
}DropDownList1先从table里绑定一个字段,然后在第一位增加一个空项,然后按button测试一下
发现,无论选了哪个项,按了button之后,DropDownList1都会返回空项,,导致无法添加sql语句问题是发生在哪里?
DropDownList1.Items.Insert(0, item);
这两行代码改了,
ListItem item = new ListItem("", "");
item.Selected = true;
DropDownList1.Items.Add(item);
应该这样写
if(!IsPostBack){
DropDownList1.DataBind();
ListItem item = new ListItem("", "");
DropDownList1.Items.Insert(0, item); }
改为 DropDownList1.SelectedItem.Text
不管是否提交,都会先执行Page_Load方法
所以你点Button,都会重新绑定DropDownList1导致DropDownList1.Text变回成默认的第一项
所以,在绑定前要判断是否回发
{
DropDownList1.DataBind();
ListItem item = new ListItem("", "");
DropDownList1.Items.Insert(0, item);
}
{
}按钮点击 是先page_load 逛一次, 在button事件中的代码