none
DataSet Conditions working but changes are not visible on Webpage RRS feed

  • Question

  • I am trying to make a wishlist option in my project I followed an online tutorial to implement it and its working just fine. I am using repeater control to show data with an image-button. In this on image button click that book should be added in wishlist and that's happening data is getting stored in the database but after storing in the database in want the button image to change to show a user that it already added. This is whole code behind of that page:

    using System;
    using System.Collections.Generic;
    using System.Data;
    using System.Data.SqlClient;
    using System.Web.UI.WebControls;
    
    namespace EReader.EReader
    {
        public partial class Books : System.Web.UI.Page
        {
            SqlConnection con = new SqlConnection(@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\EReader.mdf;Integrated Security=True;Connect Timeout=30;MultipleActiveResultSets=true");
            private int PageSize = 9;
            protected void Page_Load(object sender, EventArgs e)
            {
                if (con.State == ConnectionState.Open)
                {
                    con.Close();
                }
                con.Open();
                if (!IsPostBack)
                {
                    this.GetCustomersPageWise(1);
                }
    
                if (Request.QueryString["addtofavbooks"] != null && Session["LoggedIn"] != null)
                {
                    SqlCommand cmd = con.CreateCommand();
                    cmd.CommandType = CommandType.Text;
                    cmd.CommandText = "insert into Favourite (username,bookId) values('" + Session["LoggedIn"].ToString() + "'," + Request.QueryString["addtofavbooks"].ToString() + ")";
                    cmd.ExecuteNonQuery();
                    Response.Write("<script>alert('Product Added in Wishlist');</script>");
                }
    
                if (Session["LoggedIn"] == null)
                {
                    if (Request.QueryString["addtofavbooks"] != null)
                    {
                        Response.Write("<script>alert('Login to Your Account First. No Product Added in WishList');</script>");
                    }
                }
                else
                {
                    fullnametop.Text = Session["LoggedIn"].ToString();
                }
            }
            protected void books_ItemDataBound(object source, RepeaterItemEventArgs e)
            {
                if (Session["LoggedIn"] != null)
                {
                    Label bookid = e.Item.FindControl("bookid") as Label;
                    ImageButton addfavourite = e.Item.FindControl("addfavourite") as ImageButton;
                    SqlCommand cmd = con.CreateCommand();
                    cmd.CommandType = CommandType.Text;
                    cmd.CommandText = "select * from Favourite where bookId=@bookid and username=@username";
                    cmd.Parameters.AddWithValue("@bookid", bookid.Text);
                    cmd.Parameters.AddWithValue("@username", Session["LoggedIn"].ToString());
                    SqlDataAdapter sda = new SqlDataAdapter();
                    sda.SelectCommand = cmd;
                    DataSet ds = new DataSet();
                    sda.Fill(ds);
                    if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
                    {
                        addfavourite.ImageUrl = "/app-assets/images/liked.svg";
                        addfavourite.Enabled = false;                  
                    }
                    else
                    {
                        addfavourite.ImageUrl = "/app-assets/images/like.svg";
                    }
                }
                else
                {
                    ImageButton addfavourite = e.Item.FindControl("addfavourite") as ImageButton;
                    addfavourite.ImageUrl = "/app-assets/images/like.svg";
                }
    
                if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
                {
                    System.Web.UI.HtmlControls.HtmlContainerControl edit = (System.Web.UI.HtmlControls.HtmlContainerControl)e.Item.FindControl("edit");
                    System.Web.UI.HtmlControls.HtmlContainerControl delete = (System.Web.UI.HtmlControls.HtmlContainerControl)e.Item.FindControl("delete");
                    if (Session["LoggedIn"] == null || Session["role"].Equals("User"))
                    {
                        edit.Visible = false;
                        delete.Visible = false;
                    }
                    else
                    {
                        edit.Visible = true;
                        delete.Visible = true;
                    }
                }
            }
            protected void books_ItemCommand(object source, RepeaterCommandEventArgs e)
            {
                Response.Redirect("Books.aspx?addtofavbooks=" + e.CommandArgument.ToString());
            }
    
            private void GetCustomersPageWise(int pageIndex)
            {
                using (SqlCommand cmd = new SqlCommand("GetBooksPageWise", con))
                {
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.Parameters.AddWithValue("@PageIndex", pageIndex);
                    cmd.Parameters.AddWithValue("@PageSize", PageSize);
                    cmd.Parameters.Add("@RecordCount", SqlDbType.Int, 4);
                    cmd.Parameters["@RecordCount"].Direction = ParameterDirection.Output;
                    IDataReader idr = cmd.ExecuteReader();
                    books.DataSource = idr;
                    books.DataBind();
                    idr.Close();
                    int recordCount = Convert.ToInt32(cmd.Parameters["@RecordCount"].Value);
                    this.PopulatePager(recordCount, pageIndex);
                }
            }
            private void PopulatePager(int recordCount, int currentPage)
            {
                double dbPageCount = (double)((decimal)recordCount / Convert.ToDecimal(PageSize));
                int pageCount = (int)Math.Ceiling(dbPageCount);
                List<ListItem> pages = new List<ListItem>();
                if (pageCount > 0)
                {
                    for (int i = 1; i <= pageCount; i++)
                    {
                        pages.Add(new ListItem(i.ToString(), i.ToString(), i != currentPage));
                    }
                    if (currentPage == 1)
                    {
                        prev.Visible = false;
                    }
                    else
                    {
                        prev.CommandArgument = (currentPage - 1).ToString();
                        prev.Visible = true;
                    }
                    if (currentPage >= dbPageCount)
                    {
                        next.Visible = false;
                    }
                    else
                    {
                        next.CommandArgument = (currentPage + 1).ToString();
                        next.Visible = true;
                    }
                }
                pager.DataSource = pages;
                pager.DataBind();
            }
            protected void Page_Changed(object sender, EventArgs e)
            {
                int pageIndex = int.Parse((sender as LinkButton).CommandArgument);
                this.GetCustomersPageWise(pageIndex);
            }
        }
    }
    In this, as you can see if the image button is clicked and if that book is not in the wishlist table then it will show like.svg image but if it's in some user's wishlist then it should show liked.svg but when I run the project and add a book to wishlist it still shows the like.svg same image. Please help me out in this if possible.


    • Moved by CoolDadTx Friday, January 3, 2020 3:56 PM ASP.NET related
    • Edited by Hrithik Gajmal Friday, January 3, 2020 4:50 PM
    Wednesday, January 1, 2020 9:31 AM

All replies

  • Maybe you should move

    if( ! IsPostBack )

    {

       this.GetCustomersPageWise(1);

    }

    to the end of Page_Load.

    Wednesday, January 1, 2020 3:48 PM
  • I tired as you said i moved that part of code to the bottom of the page load but still the same, after login even if the book is in favs its still showing the white heart image not the red one. Or can you help create me a wishlist coding based on my situation.
    Wednesday, January 1, 2020 6:19 PM
  • Hi Hrithik Gajmal,
    Based on your code and description, I can't reproduce your problem.
    Regarding logic problems, I suggest you break the points yourself to debug and solve.
    If you can't solve your problem yet, please post your complete code that  can reproduce your question(Include aspx code).
    Best Regards,
    Daniel Zhang


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Friday, January 3, 2020 7:10 AM
  • This forum is for C#-specific questions only. Please post questions related to ASP.NET Core in the ASP.NET forums.

    Michael Taylor http://www.michaeltaylorp3.net

    Friday, January 3, 2020 3:56 PM
  • As you can see i have used ImageButton which should change its image when the DataBound logic is executed.

    <section id="ecommerce-products" class="grid-view">
                                <asp:Repeater ID="books" runat="server" OnItemDataBound="books_ItemDataBound" OnItemCommand="books_ItemCommand">
                                    <ItemTemplate>
                                        <div class="card ecommerce-card">
                                            <div class="card-content">
                                                <div class="item-img text-center" style="padding-top: 1rem; padding-bottom: 1rem;">
                                                    <a href="Book?id=<%#Eval("bookId") %>">
                                                        <img class="img-fluid" src="<%#Eval("bookimage") %>" style="height: 250px"></a>
                                                </div>
                                                <div class="card-body">
                                                    <div class="item-wrapper">
                                                        <div class="item-rating">
                                                            <div class="badge badge-primary badge-md">
                                                                <span>4</span> <i class="feather icon-star"></i>
                                                            </div>
                                                        </div>
                                                        <div class="item-price" style="top: 0px;">
                                                            <div class="badge badge-primary badge-md">
                                                                <i class="feather icon-file-text" style="margin-right: 0.25rem; margin-left: 0rem;"></i><span><%#Eval("bookpages") %></span>
                                                            </div>
                                                        </div>
                                                    </div>
                                                    <div class="item-name">
                                                        <span data-toggle="tooltip" data-trigger="hover" data-placement="auto" data-original-title="<%#Eval("bookname") %> by <%#Eval("bookauthor") %> | <%#Eval("bookpublisher") %>"><span><%#Eval("bookname") %></span> <i>by</i> <span class="company-name"><%#Eval("bookauthor") %> | <%#Eval("bookpublisher") %></span></span>
                                                        <asp:Label ID="bookid" runat="server"></asp:Label>
                                                    </div>
                                                    <div>
                                                        <p class="item-description" data-toggle="tooltip" data-trigger="hover" data-placement="auto" data-original-title="<%#Eval("bookdesc") %>"><%#Eval("bookdesc") %></p>
                                                    </div>
                                                </div>
                                                <div class="item-options text-center">
                                                    <div class="item-wrapper">
                                                        <div class="item-rating">
                                                            <div class="badge badge-primary badge-md">
                                                                <span>4</span> <i class="feather icon-star"></i>
                                                            </div>
                                                        </div>
                                                    </div>
                                                    <div id="edit" runat="server" class="wishlist col-md-6">
                                                        <a id="editbooks" href="Edit-Book?id=<%#Eval("bookId") %>"><i class="feather icon-edit"></i><span>Edit</span></a>
                                                    </div>
                                                    <div class="wishlist col-md-6" style="cursor:default">
                                                        <asp:ImageButton ID="addfavourite" runat="server" CommandArgument='<%# Eval("bookId")%>' CommandName="addtofavbooks" Height="25" />
                                                    </div>
                                                    <div id="delete" runat="server" class="cart col-md-6" style="background-color: #EA5455">
                                                        <i class="feather icon-trash-2"></i><span class="add-to-cart">Remove</span> <a id="deletebook" href="Delete-Book?id=<%#Eval("bookId") %>" class="view-in-cart d-none">Sure?</a>
                                                    </div>
                                                    <div class="cart col-md-6">
                                                        <i class="feather icon-trash-2"></i><span class="add-to-cart">Remove</span>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </ItemTemplate>
                                </asp:Repeater>
                            </section>
                            <!-- Ecommerce Products Ends -->
    
                            <!-- Ecommerce Pagination Starts -->
                            <section id="ecommerce-pagination">
                                <div class="row">
                                    <div class="col-sm-12">
                                        <nav aria-label="Page navigation example">
                                            <ul class="pagination justify-content-center mt-2">
                                                <li class="page-item prev-item">
                                                    <asp:LinkButton ID="prev" runat="server" CssClass="page-link feather icon-chevrons-left" CausesValidation="false" CommandArgument='<%# Eval("Text") %>'
                                                        OnClick="Page_Changed" Visible="false" ToolTip="Prev"
                                                        Font-Bold="true">
                                                    </asp:LinkButton>
                                                </li>
                                                <asp:Repeater ID="pager" runat="server">
                                                    <ItemTemplate>
                                                        <li class="page-item active">
                                                            <asp:LinkButton ID="page" runat="server" Text='<%#Eval("Text") %>' CommandArgument='<%# Eval("Value") %>'
                                                                CssClass='<%# Convert.ToBoolean(Eval("Enabled")) ? "page-change" : "page-link" %>'
                                                                OnClick="Page_Changed" OnClientClick='<%# !Convert.ToBoolean(Eval("Enabled")) ? "return false;" : "" %>'></asp:LinkButton>
                                                        </li>
                                                    </ItemTemplate>
                                                </asp:Repeater>
                                                <li class="page-item next-item">
                                                    <asp:LinkButton ID="next" runat="server" CssClass="page-link feather icon-chevrons-right" CausesValidation="false" CommandArgument='<%# Eval("Text") %>'
                                                        OnClick="Page_Changed" Visible="false" ToolTip="Next"
                                                        Font-Bold="true">
                                                    </asp:LinkButton>
                                                </li>
                                            </ul>
                                        </nav>
                                    </div>
                                </div>
                            </section>

    Friday, January 3, 2020 5:06 PM