Inderpal Singh
Inderpal Singh

Reputation: 270

generating new column in grid view for checkbox column

i am using datatable as data source for grid view

     DataTable table = new DataTable();
    table.Columns.Add("Dosage", typeof(int));
    table.Columns.Add("Drug", typeof(string));
    table.Columns.Add("Patient", typeof(string));
    table.Columns.Add("Select",typeof(bool));


    //
    // Here we add five DataRows.
    //
    table.Rows.Add(25, "Indocin", "David");
    table.Rows.Add(50, "Enebrel", "Sam");
    table.Rows.Add(10, "Hydralazine", "Christoff");
    table.Rows.Add(21, "Combivent", "Janet");
    table.Rows.Add(100, "Dilantin", "Melanie");


    GridView2.DataSource = table;


    GridView2.DataBind();   

at page load and i want to create new column in grid to add radio button

actually i want to submit row values for selected check boxes in database..

Upvotes: 2

Views: 1104

Answers (1)

Tim Schmelter
Tim Schmelter

Reputation: 460068

If you want to add a new column to the GridView you should add it to it's DataSource. Either by selecting another column from the database or, if you use an in-memory DataTable as here- by adding another DataColumn. But i assume that you already have added the column(Select).

Then use a TemplateField to add the RadioButton and eval/bind it to the column.

<asp:GridView ID="GridView2" runat="server" AutoGenerateColumns="False" OnRowDataBound="GridView2_RowDataBound" >
         <Columns>
            <asp:TemplateField HeaderText="Select">
                  <ItemTemplate>
                     <asp:RadioButton ID="rbSelect"   runat="server" />
                  </ItemTemplate>
            </asp:TemplateField>

You can use RowDataBound to check it according to the datasource:

protected void GridView2_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        var rbSelect = (RadioButton)e.Row.FindControl("rbSelect");
        var row = ((DataRowView)e.Row.DataItem).Row;
        rbSelect.Checked = row.Field<bool>("Select");
    }
}

Upvotes: 2

Related Questions