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语句问题是发生在哪里?

解决方案 »

  1.   

     if (DropDownList1.Text != "")这句是错的
      

  2.   

    ListItem item = new ListItem("", "");
            DropDownList1.Items.Insert(0, item);  
    这两行代码改了,
    ListItem item = new ListItem("", "");
                item.Selected = true;
            DropDownList1.Items.Add(item); 
      

  3.   

    if(DropDownList1.SelectedItem.Text !="")
    应该这样写
      

  4.   


    if(!IsPostBack){
            DropDownList1.DataBind();
            ListItem item = new ListItem("", "");
            DropDownList1.Items.Insert(0, item);  }
      

  5.   


    改为 DropDownList1.SelectedItem.Text
      

  6.   

    首先,你要了解ASP.NEt页面的生命周期
    不管是否提交,都会先执行Page_Load方法
    所以你点Button,都会重新绑定DropDownList1导致DropDownList1.Text变回成默认的第一项
    所以,在绑定前要判断是否回发
      

  7.   

    if(!ispostback)
    {
     DropDownList1.DataBind();
            ListItem item = new ListItem("", "");
            DropDownList1.Items.Insert(0, item);  
    }
      

  8.   

    if(!ispostback) 
    {
    }按钮点击  是先page_load 逛一次, 在button事件中的代码