wormwood wormwood - 3 years ago 110
ASP.NET (C#) Question

Adding a checkbox in a table cell

Is this possible?

I have a table with user accounts retrieved from a database. Then at the start of each column I would like to add a checkbox which if selected will select the account. I tried experimenting with it and I can't seem to put the checkbox inside the table. How can I do this?

Answer Source

You can try this:

 const int ColumnSelect = 0;

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

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

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.
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download