0

i need to add checkbox column to my gridview in c#.

i have my code:

               foreach (GridViewRow objRow in GrdDynamicControls.Rows)
                {
                    if (dttableDetails.Columns.Contains(strColumnName))
                    {
                        position = dttableDetails.Columns[strColumnName].Ordinal;

                        if (strtype.Contains("CheckBox"))
                        {
                            try
                            {

                              GrdDynamicControls.Rows[i].Cells.RemoveAt(position);

                                chkCheckBox.ID = strControlName;

                                chkCheckBox.AutoPostBack = true;
                                tcCheckCell.Controls.Add(chkCheckBox);

                                 objRow.Cells.Add(tcCheckCell);
                              //  GrdDynamicControls.Rows[i].Cells.AddAt(position, tcCheckCell);
                            }
                            catch { }
                            chkCheckBox.CheckedChanged += new EventHandler(chkCheckBox_CheckedChanged);



                        }


                    }
            }

but this is overwritting the checkbox for each objrow in gridview. im not able to get the checkbox for that particular column for all the rows in gridview.pls help...

Innova
  • 4,831
  • 21
  • 76
  • 107
  • no im creating the controls dynamically.it is not oly checkbox.ill get even dropdownlist too. so that for dynamic bindings in gridview i have used the code to create checkbox – Innova Jun 23 '10 at 13:56

3 Answers3

1

Why not use the TemplateField control in the markup, and define the checkbox in the template instead? It would be easier to manage...

<asp:GridVIew ...>

  <Columns>
     <asp:TemplateField ..>
        <asp:CheckBox .. />
     </asp:TemplateField>
  </Columns>
</asp:GridVIew>

And just set everything up in the markup

Brian Mains
  • 50,520
  • 35
  • 148
  • 257
0

Try using OnRowDataBound event on the gridview. You can use it to specify what control you want to use for each row. Here's a link that explains it with an example.

http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridview.rowdatabound.aspx

Dan H
  • 1,828
  • 2
  • 21
  • 38
-1

Use the TemplateField control in the markup, and define the checkbox in the template instead:

<asp:TemplateField HeaderText="Delete" ItemStyle-Width="39px">
    <ItemTemplate>
        <center>
            <asp:CheckBox ID="chkDelete" runat="server" />
        </center>
    </ItemTemplate>
</asp:TemplateField>
BDL
  • 21,052
  • 22
  • 49
  • 55