mercredi 14 juin 2023

How can I check a checkbox in gridview based on a condition?

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?




Aucun commentaire:

Enregistrer un commentaire