How to tackle checked event in DataGrid checkboxs

578 Views Asked by At

I need to fill a DataGrid with DataTable object as DataSource. Its perfect, I can do this but, I stuck with CheckBox requirement in each Row. I know DataGridView provides DataGridViewCheckBoxColumn but, I want the same for DataGrid.

I got a solution, something like this -

        DataTable dt = new DataTable("Books");

        DataColumn dc1 = new DataColumn("Name", typeof(System.String));
        DataColumn dc2 = new DataColumn("ISBN", typeof(System.String));
        DataColumn dc3 = new DataColumn("Price", typeof(System.Int32));
        DataColumn dc4 = new DataColumn("Author", typeof(System.String));

        DataColumn dcSelectToDelete = new DataColumn("Select");
        dcSelectToDelete.DataType = System.Type.GetType("System.Boolean");
        dcSelectToDelete.DefaultValue = false;

        dt.Columns.Add(dc1);
        dt.Columns.Add(dc2);
        dt.Columns.Add(dc3);
        dt.Columns.Add(dc4);
        dt.Columns.Add(dcSelectToDelete);

        drd.DataSource = dt;

But I am not sure for the correctness of this code.Also If it works, I dont know, How to tackle Checked event of checkBoxes.

Kindly suggest the correct solution for DataGrid (Not DataGridView).

If I will fill the datatable by certain list. How will I dynamically add CheckBox in each column?

2

There are 2 best solutions below

2
On

Is there any reason for you to use DataGrid instead of GridView which is certainly better and more capable conrtrol?

Regardless, to show Check Box in DataGrid, you need to use TemplateColumn. In case, you are using auto generation of columns then you need to switch if off and instead specify all columns manually. For example,

<asp:DataGrid id="MyDataGrid" runat="server" AutoGenerateColumns="false" ... >
   <Columns>
       <asp:BoundColumn HeaderText="Name" DataField="Name"/>
       <asp:BoundColumn HeaderText="ISBN" DataField="ISBN"/>
       ...
       <asp:TemplateColumn>
          <ItemTemplate>
             <asp:CheckBox ID="SelectRow" runat="server" 
                Checked='<%# DataBinder.Eval(Container.DataItem, "Select") %>' />
          </ItemTemplate>
   </Columns>
</asp:DataGrid>

The data-table code would remain same as you have posted - the checked property of check-box is set as per the value in select column.

1
On

How about you use DataGridTemplateColumn (as in WPF DataGrid) and within it put a check box with Checked and UnChecked events or whatever event then handle this in the code behind. e.g in WPF add within DataGrid.Columns

<DataGridTemplateColumn  >
     <DataGridTemplateColumn.CellTemplate>
           <DataTemplate>
                <CheckBox x:Name="chkSelect" Checked="chkSelect_Checked" Unchecked="chkSelect_Unchecked" />
           </DataTemplate>
     </DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn> 

Also, you have not specified technology as WPF, ASP or other.