如何在asp.net 4.0中绑定可编辑网格视图中的复选框

本文关键字:编辑 网格 视图 复选框 绑定 asp net | 更新日期: 2023-09-27 18:06:34

我有可编辑的网格视图,其中有与数据行绑定的复选框。这里我输入code:

 protected void GV_ViewCustomers_RowDataBound(object sender, GridViewRowEventArgs e)
    { 
        if (e.Row.RowType == DataControlRowType.DataRow && e.Row.RowState != DataControlRowState.Edit)
    {
        using (DataClassesDataContext db = new DataClassesDataContext())
        {
            DropDownList ddl = (DropDownList)e.Row.FindControl("DDL_Types");
            ddl.DataSource = db.PartyTypes.Select(p => p).ToList();
            ddl.DataBind();
            ddl.SelectedValue = DataBinder.Eval(e.Row.DataItem, "type_id").ToString();
            DropDownList ddl1 = (DropDownList)e.Row.FindControl("DDL_CountryNames");
            ddl1.DataSource = db.Countries.Select(c => c).ToList();
            ddl1.DataBind();
            if (!string.IsNullOrEmpty(DataBinder.Eval(e.Row.DataItem, "country_id").ToString()))
            {
                ddl1.SelectedValue = DataBinder.Eval(e.Row.DataItem, "country_id").ToString();
                DropDownList ddl2 = (DropDownList)e.Row.FindControl("DDL_StateNames");
                ddl2.DataSource = db.States.Where(s => s.country_id.Equals(int.Parse(DataBinder.Eval(e.Row.DataItem, "country_id").ToString()))).Select(s => s).ToList();
                ddl2.DataBind();
                ddl2.SelectedValue = DataBinder.Eval(e.Row.DataItem, "state_id").ToString();
            }
        }
        DataRowView rowView1 = (DataRowView)e.Row.DataItem;
        if (rowView1["UserOFC"] != null)
        {
            (e.Row.FindControl("chk_UserOFC") as CheckBox).Checked = Convert.ToBoolean(e.Row.DataItem.Equals("UserOFC").ToString());
        }
        if (rowView1["UserVAT"] != null)
        {
            (e.Row.FindControl("chk_UserVAT") as CheckBox).Checked = Convert.ToBoolean(e.Row.DataItem.Equals("UserVAT").ToString());
        }
        if (rowView1["UserINV"] != null)
        {
            (e.Row.FindControl("chk_UserINV") as CheckBox).Checked = Convert.ToBoolean(e.Row.DataItem.Equals("UserINV").ToString());
        }
        if (rowView1["UserNone"] != null)
        {
            (e.Row.FindControl("chk_UserNone") as CheckBox).Checked = Convert.ToBoolean(e.Row.DataItem.Equals("UserNone").ToString());
        }
    }
    }

这所有复选框的值来自允许null数据列,所以需要绑定他们从网格视图行数据绑定

如何在asp.net 4.0中绑定可编辑网格视图中的复选框

不是答案,但它应该有助于调试,以了解问题所在。将分配CheckBox控件的checked属性的逻辑分开,并使用调试器检查分配给checked属性的内容。

CheckBox chk_UserOFC = e.Row.FindControl("chk_UserOFC") as CheckBox;
bool UserOFC = Convert.ToBoolean(e.Row.DataItem.Equals("UserOFC").ToString());
chk_UserOFC.Checked = UserOFC;

还有,为什么要使用e.l row . dataitem。Equals,返回bool值,然后将其强制转换为字符串,然后使用Convert。ToBoolean获取bool值?我想你也可以这样用:

bool UserOFC = e.Row.DataItem.Equals("UserOFC");