I have gridview on an aspx page (web form) with a check box and Id (the Id's are from a table of Id's). In the code behind the page (c#), I get a list of Id's. I want that all of the check boxes that are next to an Id that is on the list to be checked.
I tried this:
public localhost.WebService1 w = new localhost.WebService1();
public localhost.User u = new localhost.User();
if (!IsPostBack)
{
this.GridView.DataSource = w.SelectListOfIds();
this.GridView.DataBind();
int[] ei = w.SelectListOfIDSOfUser(u.UserId);
for (int i = 0; i < ei.Length; i++)
{
int id = ei[i];
foreach (GridViewRow row in GridView.Rows)
{
Label l = (Label)row.FindControl("Id");
if (l.Text != null)
{
int cId = Convert.ToInt32(l.Text);
if (cId == id)
{
CheckBox checkbox = (CheckBox)row.FindControl("CheckBox1") as CheckBox;
checkbox.Checked = true;
}
}
}
}
}
This is my gridview:
<asp:GridView ID="GridView" showheader=false runat="server" BorderWidth="1px" CellPadding="4" ForeColor="Black" GridLines="Horizontal" AutoGenerateColumns="false" AllowPaging="true" CssClass="wrapper5">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="CheckBox1" runat="server"/>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="Id" Text='<% #Eval("id") %>' runat="server"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
I get the error: reference to an object not set to an object instance on checkbox.Checked = true;.
Is there a way to do this?
Ok, since the int[] array list of items is obviosuly not going to be the same lenght (rows) as the data for the GridView, then I suggest this approach.
First, sample markup. Note that as a general rule, you do NOT have to include the row PK database ID, but should use Datakeys (so you don't include nor expose database primary keys values in the client side markup for reasons of security).
However, for this example, I'll include the ID in the markup, but you don't have to, and as noted, should use datakeys[].
So, this markup:
And code behind is this:
So, we use a "contains" on that array, since length of the array is unknown, and I don't want to use a loop or for/next for that.
The result is thus this:
As noted, as a general rule, you don't need nor want to expose the database row PK id to the gridview or client side.
So, note the use of data keys setting in the GridView markup.
Thus, removing the "id" from the row, we have this GridView now:
And our code now becomes this:
And the results are much the same, but without the PK ID exposed, and thus we get/see this: