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?

7
  • Why you can't add an ID to the checkbox? Commented Mar 24, 2015 at 22:18
  • Here you can see how to find controls inside the GridView: stackoverflow.com/questions/6873973/… Commented Mar 24, 2015 at 22:21
  • @nZeus you can't add an id to asp:CheckBoxField, i wish i could Commented Mar 24, 2015 at 22:22
  • What event do you have this foreach implemented? Commented Mar 24, 2015 at 22:23
  • You can use <asp:TemplateField> and place Checkbox control inside Commented Mar 24, 2015 at 22:25

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

I wouldn't recommend this solution. Using indexes is not a good idea.
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.
@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.

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.