1

我在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();
4

2 回答 2

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

}

于 2013-09-20T19:05:54.103 回答
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;
    }
}
于 2013-09-21T02:59:10.357 回答