0

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?

1 Answer 1

5

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.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.
        }
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

But the data will be retrieved from the database.
What I want to do is if the checkbox from the column is checked then the column will be selected.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.