1

My code

<asp:GridView ID="FireFighters" runat="server" AutoGenerateColumns="false"  OnRowDataBound="FireFighters_RowDataBound"  >
    <Columns>
        <asp:BoundField HeaderText="שם הכבאי" DataField="username" />
        <asp:CheckBoxField HeaderText="מצוות לאירוע" DataField="IsLinked"  />
    </Columns>
</asp:GridView>

I can't add and id to the asp:CheckBoxField, i tried calling it like this from code-behind:

foreach(GridViewRow gvr in FireFighters.Rows)
{
    lst.Add(new FireFighter{username=gvr.Attributes["id"].ToString(),IsLinked=((gvr.Cells[1] as Control) as CheckBox).Checked});
}

But its null, how can i get the value(checked or not) of the Checkbox?

Tomer Oszlak
  • 245
  • 1
  • 4
  • 9

1 Answers1

1

You are almost there. This should help you:

foreach (GridViewRow gvr in FireFighters.Rows)
{
    lst.Add(new MyClass { username = ((DataControlFieldCell)gvr.Controls[0]).Text, IsLinked = ((CheckBox)gvr.Controls[1].Controls[0]).Checked });
}

Each row has a collection of cells, and these cells have the controls you want inside. You can access them by index (in the case of the checkbox) and cast it to a CheckBox or access the cells themselves and get the text and cast it to DataControlFieldCell.

Hanlet Escaño
  • 17,114
  • 8
  • 52
  • 75
  • I wouldn't recommend this solution. Using indexes is not a good idea. – nZeus Mar 24 '15 at 22:38
  • I know it is not the best idea since the code can change. He was already doing it this way, I just pointed him in the right direction. Feel free to add your own - better - solution. – Hanlet Escaño Mar 24 '15 at 22:39
  • 1
    @TomerOszlak as nZeus mentions, you have to have in mind that if something in your markup changes this will not work, and thus this is not the best solution to your problem. You should probably use something where you can find the controls inside your grid. – Hanlet Escaño Mar 24 '15 at 22:43