mercredi 14 juin 2023

How can I give check box in gridview a value that is not from the data source?

I have this gridview on an aspx page (Web form):

<asp:GridView ID="GridView" runat="server" showheader=false BorderStyle="None"CellPadding="4" GridLines="Horizontal" AutoGenerateColumns="false" AllowPaging="true" CssClass="wrapper5">
                        <Columns>
                            <asp:TemplateField>
                                <ItemTemplate>
                                    <asp:CheckBox ID="CheckBoxFR" runat="server"/>
                                </ItemTemplate>
                            </asp:TemplateField>
                            <asp:TemplateField>
                                <ItemTemplate>
                                    <asp:Label ID="itemName" Text='<% # Eval("itemName") %>' runat="server"></asp:Label>
                                </ItemTemplate>
                            </asp:TemplateField>
                            <asp:TemplateField>
                                <ItemTemplate>
                                    <asp:Label ID="itemId" Text='<% #Eval("itemId") %>' runat="server" Visible="false"></asp:Label>
                                </ItemTemplate>
                            </asp:TemplateField>
                        </Columns>
                        </asp:GridView>

I have an array of itemIds that the user has. I want that the checkboxes in the same row as the itemIds will be checkd if the itemId is in the array.

This is what I tried in the code behind in c#:

public localhost.WebService1 w = new localhost.WebService1();
        public localhost.Item i = new localhost.Item();
        public localhost.MyUser u = new localhost.MyUser();

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                int[] ei = w.SelectListOfUsersItemsIDS(1); //user number 1
                this.GridViewVG.DataSource = w.SelectListOfItems();
                this.GridViewVG.DataBind();
                for (int i = 0; i < ei.Length; i++)
                {
                    int item = ei[i];
                    foreach (GridViewRow row in GridView.Rows)
                    {
                        Label l = (Label)row.FindControl("itemId");
                        if (l.Text != null)
                        {
                            int itemId = Convert.ToInt32(l.Text);
                            if (itemId == item)
                            {
                                CheckBox checkbox = (CheckBox)row.FindControl("CheckBoxFR") as CheckBox;
                                checkbox.Checked = true;
                            }
                        }
                    }
                }

I also tried using private bool active; and changing it to true when checking if (itemId == item) and it didn't work.

How can I do this?




Aucun commentaire:

Enregistrer un commentaire