在表格单元格中添加复选框

时间:2013-08-22 05:38:13

标签: asp.net checkbox

这可能吗?

我有一个表,其中包含从数据库中检索到的用户帐户。然后在每列的开头我想添加一个复选框,如果选中该复选框将选择该帐户。我试过试验它,我似乎无法将复选框放在表格内。我怎么能这样做?

1 个答案:

答案 0 :(得分:5)

你可以试试这个:

 const int ColumnSelect = 0;

protected void Page_Load(object sender, EventArgs e)
{       
    //Get real data here.
    DataTable dt = new DataTable();
    dt.Columns.Add("count");                
    dt.Rows.Add(dt.NewRow());
    dt.Rows[0][0] = "5";

    GridView1.Columns.Add(new TemplateField());        
    BoundField b = new BoundField();
    GridView1.Columns.Add(b);
    b.DataField = "count";
    GridView1.DataSource = dt;
    GridView1.DataBind();
}


protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType != DataControlRowType.Header)
    {            
        e.Row.Cells[ColumnSelect].Controls.Add(new CheckBox());
    }
}

protected void Button1_Click(object sender, EventArgs e)
{
    foreach(GridViewRow row in GridView1.Rows)
    {
        //Could also use (CheckBox)row.Cells[ColumnSelect].FindControl if you give the checkboxes IDs when generating them.
        CheckBox cb = (CheckBox)row.Cells[ColumnSelect].Controls[0];

        if (cb.Checked)
        {
            //Do something here.
        }
    }
}