Quantcast
Channel: Windows Forms Data Controls and Databinding forum
Viewing all articles
Browse latest Browse all 2535

Index was out of range. Must be non-negative and less than the size of the collection.

$
0
0

 protected void Checkout_Click(object sender, EventArgs e)
        {
            if (Session["Cart"] != null)
            Response.Redirect("Checkout.aspx");
        }

        protected void AddToCart_Click(object sender, EventArgs e)
        {

            var selectedProducts = Products.Rows.Cast<GridViewRow>()
           .Where(row => ((CheckBox)row.FindControl("SelectedProducts")).Checked)
           .Select(row => Products.DataKeys[row.RowIndex].Value.ToString()).ToList();

            if (Session["Cart"] == null)
            {
                Session["Cart"] = selectedProducts;
            }
            else
            {
                var cart = (List<string>)Session["Cart"];
                foreach (var product in selectedProducts)
                cart.Add(product);
                Session["Cart"] = cart;
            }
            foreach (GridViewRow row in Products.Rows)
            {
                CheckBox cb = (CheckBox)row.FindControl("SelectedProducts");
                if (cb.Checked)
                    cb.Checked = false;
            }

        }

and my front-end code is

<asp:GridView ID="Products" runat="server" AutoGenerateColumns="False" DataSourceID="SqlDataSource1" GridLines="None" EnableViewState="False">
            <Columns>
                <asp:TemplateField HeaderText="Add To Cart">
                    <ItemTemplate>
                        <asp:CheckBox ID="SelectedProducts" runat="server" />
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:BoundField DataField="sProdName" HeaderText="Product Name" SortExpression="sProdName" />
                <asp:BoundField DataField="sPrice" HeaderText="Price" SortExpression="sPrice" DataFormatString="{0:c}" />
            </Columns>
        </asp:GridView>
        <asp:Button ID="AddToCart" runat="server" Text="Select Products" OnClick="AddToCart_Click" />
        <asp:Button ID="Checkout" runat="server" Text="Check Out" OnClick="Checkout_Click" />
        <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:connstring %>" ProviderName="<%$ ConnectionStrings:connstring.ProviderName %>" SelectCommand="SELECT [sProdName], [sPrice] FROM [ProdDet]"></asp:SqlDataSource>

                        

Viewing all articles
Browse latest Browse all 2535

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>