如何在GridView中动态启用CheckBoxField?

时间:2013-09-20 17:42:55

标签: c# asp.net gridview

我动态地在 GridView 中生成 CheckBoxField 。但在输出中,CheckBox 禁用 如何动态启用 CheckBox 我知道如果在GridView标记中添加一个TemplateField,我的问题就解决了,但我不会在GridView中添加TemplateField

ASPX:

 <asp:GridView ID="GridView2" runat="server">
    </asp:GridView>

代码背后:

    DataTable dTable = new DataTable();
    dTable.Columns.Add("c1", typeof(bool));
    DataRow r = dTable.NewRow();
    r[0] = false;        
    dTable.Rows.Add(r);
    r = dTable.NewRow();
    r[0] = true;
    dTable.Rows.Add(r);

    CheckBoxField chkField = new CheckBoxField();
    chkField.DataField = "c1";
    chkField.HeaderText = "CheckBox";
    chkField.ReadOnly = false;
    GridView2.Columns.Add(chkField);
    GridView2.DataSource = dTable;
    GridView2.DataBind();

2 个答案:

答案 0 :(得分:2)

我将代码放在RowDataBound事件中以启用复选框:

protected void Page_Load(object sender, EventArgs e)
{
    this.GridView2.RowDataBound += GridView2_RowDataBound;

    BindGrid();
}

void GridView2_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.Cells[0].GetType() == typeof(System.Web.UI.WebControls.DataControlFieldCell))
    {
        TableCell tc = e.Row.Cells[0];
        if (tc.Controls.Count > 0)
        {
            CheckBox cb = (CheckBox)tc.Controls[0];
            if (!(cb == null))
            {
                cb.Enabled = true;
            }
        }
    }
}


private void BindGrid()
{
    DataTable dTable = new DataTable();
    dTable.Columns.Add("c1", typeof(bool));
    DataRow r = dTable.NewRow();
    r[0] = false;
    dTable.Rows.Add(r);
    r = dTable.NewRow();
    r[0] = true;
    dTable.Rows.Add(r);

    //CheckBoxField chkField = new CheckBoxField();
    //chkField.DataField = "c1";
    //chkField.HeaderText = "CheckBox";
    //chkField.ReadOnly = false;
    //GridView1.Columns.Add(chkField);
    GridView2.DataSource = dTable;
    GridView2.DataBind();
}

}

答案 1 :(得分:0)

优化Decker97回答:

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        BindGrid();
    }
}
protected void BindGrid()
{
    DataTable dTable = new DataTable();
    dTable.Columns.Add("c1", typeof(bool));
    DataRow r = dTable.NewRow();
    r[0] = false;
    dTable.Rows.Add(r);
    r = dTable.NewRow();
    r[0] = true;
    dTable.Rows.Add(r);
    GridView2.DataSource = dTable;
    GridView2.DataBind();
}
protected void GridView2_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        CheckBox cb = (CheckBox)e.Row.Cells[0].Controls[0];
        cb.Enabled = true;
    }
}
相关问题