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

时间:2014-06-04 13:43:20

标签: c# gridview asp.net-4.0

我有可编辑的网格视图,其中包含与数据行绑定的复选框。在这里我把代码:

 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());
        }
    }
    }

这个所有复选框值都来自allow null data column,因此需要从网格视图行数据绑定它们。

1 个答案:

答案 0 :(得分: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.Row.DataItem.Equals,它返回一个bool,然后将其转换为字符串,然后使用Convert.ToBoolean来获取bool?我想你可以用同样的方法:

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