Add record to Database if Button text is Add and Delete record form Database if Button text is Added using C# in ASP.Net

Last Reply 8 months ago By Indresh

Posted 8 months ago

i want to modify this code in below link, the Added button that shows when Add button is clicked, i want to make the Added button to delet the recode added

 

http://www.aspforums.net/Threads/107995/How-to-add-items-and-check-added-items-in-DataList-like-Shopping-Cart-in-ASPNet/

 

<div>
    <table border="0" cellpadding="0" cellspacing="0">
        <tr>
            <td>
                UserName
            </td>
            <td>
                <asp:TextBox ID="txtUserName" runat="server" />
            </td>
        </tr>
        <tr>
            <td>
                Password
            </td>
            <td>
                <asp:TextBox ID="txtPassword" TextMode="Password" runat="server" />
            </td>
        </tr>
        <tr>
            <td colspan="2">
                <asp:Button ID="btnSubmit" Text="Login" OnClick="OnLogin" runat="server" />
            </td>
        </tr>
    </table>
</div>

code

 

protected void OnLogin(object sender, EventArgs e)
{
    using (SqlConnection con = new SqlConnection(constring))
    {
        using (SqlCommand cmd = new SqlCommand("SELECT * FROM [User] WHERE UserName=@UserName AND Password=@Password", con))
        {
            cmd.Parameters.AddWithValue("@Username", txtUserName.Text.Trim());
            cmd.Parameters.AddWithValue("@Password", txtPassword.Text.Trim());
            con.Open();
            SqlDataReader idr = cmd.ExecuteReader();
            if (idr.Read())
            {
                Session["UserId"] = idr["Id"].ToString();
                Response.Redirect("Default2.aspx");
            }
            con.Close();
        }
    }
}

 

<form id="form1" runat="server">
<div>
    <asp:DataList ID="dlBooks" runat="server" OnItemDataBound="dlBooks_ItemDataBound">
        <HeaderTemplate>
            <table class="table" border="1">
                <tr>
                    <td>
                        <asp:Label Text="Book Pics" runat="server" />
                    </td>
                    <td>
                        <asp:Label ID="Label1" Text="BookName" runat="server" />
                    </td>
                    <td>
                        <asp:Label ID="Label2" Text="Favorite Book" runat="server" />
                    </td>
                </tr>
        </HeaderTemplate>
        <ItemTemplate>
            <tr>
                <td>
                    <asp:Label ID="lblId" Text='<%#Eval("Id") %>' Visible="false" runat="server" />
                    <asp:Image ID="Imagebooks" ImageUrl='<%# "Images/" + Eval("Name") %>' Width="80px"
                        Height="50px" runat="server" />
                </td>
                <td>
                    <asp:Label ID="lblbookName" Text='<%#Eval("Name")%>' runat="server" />
                </td>
                <td>
                    <asp:Button ID="btnAdd" Text="Add" OnClick="OnfavoriteBook" runat="server" />
                </td>
            </tr>
        </ItemTemplate>
        <FooterTemplate>
            </table>
        </FooterTemplate>
    </asp:DataList>
</div>
<br />
<br />
<asp:LinkButton Text="Logout" OnClick="OnLogOut" runat="server" />
</form>

 

private string constring = ConfigurationManager.ConnectionStrings["constring"].ToString();
protected void Page_Load(object sender, EventArgs e)
{
    if (!this.IsPostBack)
    {
 
        this.Populatebooks();
    }
}
 
private void Populatebooks()
{
    string userId = Session["UserId"].ToString();
 
    using (SqlConnection con = new SqlConnection(constring))
    {
 
        using (SqlCommand cmd = new SqlCommand("SELECT * FROM [dbo].[Files]", con))
        {
            DataTable dt = new DataTable();
            SqlDataAdapter sda = new SqlDataAdapter(cmd);
            sda.Fill(dt);
            dlBooks.DataSource = dt;
            dlBooks.DataBind();
        }
    }
 
}
 
protected void OnfavoriteBook(object sender, EventArgs e)
{
 
    DataListItem item = (sender as Button).NamingContainer as DataListItem;
    int bookId = Convert.ToInt32((item.FindControl("lblId") as Label).Text);
    using (SqlConnection con = new SqlConnection(constring))
    {
        if ((item.FindControl("btnAdd") as Button).Text.ToUpper() == "ADD")
        {
            using (SqlCommand cmd = new SqlCommand("INSERT INTO Dim_favorite values(@UserId,@BookId)", con))
            {
                cmd.Parameters.AddWithValue("@UserId", Session["UserId"]);
                cmd.Parameters.AddWithValue("@BookId", bookId);
                con.Open();
                cmd.ExecuteNonQuery();
                con.Close();
            }
        }
    }
 
    this.Populatebooks();
}
protected void dlBooks_ItemDataBound(object sender, DataListItemEventArgs e)
{
    if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
    {
        string bookid = (e.Item.FindControl("lblId") as Label).Text;
        using (SqlConnection con = new SqlConnection(constring))
        {
            using (SqlCommand cmd = new SqlCommand("SELECT f.Id AS TestId,f.Name,'Added' [Status] FROM Files f INNER JOIN Dim_favorite fav On f.Id = fav.BookId WHERE fav.UserId='" + Session["UserId"] + "' ", con))
            {
                DataTable dt = new DataTable();
                SqlDataAdapter sda = new SqlDataAdapter(cmd);
                sda.Fill(dt);
 
                foreach (DataRow row in dt.Rows)
                {
                    if (bookid == row["TestId"].ToString())
                    {
                        (e.Item.FindControl("btnAdd") as Button).Text = "Added";
                    }
                }
            }
        }
    }
}
 
protected void OnLogOut(object sender, EventArgs e)
{
    Response.Redirect("Login.aspx");
}

 

Posted 8 months ago

Hi micah,

I have created sample code which full-fill your requirement.

HTML

LoginPage

<div>
    <table border="0" cellpadding="0" cellspacing="0">
        <tr>
            <td>
                UserName
            </td>
            <td>
                <asp:TextBox ID="txtUserName" runat="server" />
            </td>
        </tr>
        <tr>
            <td>
                Password
            </td>
            <td>
                <asp:TextBox ID="txtPassword" TextMode="Password" runat="server" />
            </td>
        </tr>
        <tr>
            <td colspan="2">
                <asp:Button ID="btnSubmit" Text="Login" OnClick="OnLogin" runat="server" />
            </td>
        </tr>
    </table>
</div>

C#

private string constring = ConfigurationManager.ConnectionStrings["constring"].ToString();

protected void Page_Load(object sender, EventArgs e)
{
    if (!this.IsPostBack)
    {

    }
}


protected void OnLogin(object sender, EventArgs e)
{
    using (SqlConnection con = new SqlConnection(constring))
    {
        using (SqlCommand cmd = new SqlCommand("SELECT * FROM [User] WHERE UserName=@UserName AND Password=@Password", con))
        {
            cmd.Parameters.AddWithValue("@Username", txtUserName.Text.Trim());
            cmd.Parameters.AddWithValue("@Password", txtPassword.Text.Trim());
            con.Open();
            SqlDataReader idr = cmd.ExecuteReader();
            if (idr.Read())
            {
                Session["UserId"] = idr["Id"].ToString();
                Response.Redirect("Default2.aspx");
            }
            con.Close();
        }
    }
}

HTML

Default2.aspx Page

<form id="form1" runat="server">
<div>
    <asp:DataList ID="dlBooks" runat="server" OnItemDataBound="dlBooks_ItemDataBound">
        <HeaderTemplate>
            <table class="table" border="1">
                <tr>
                    <td>
                        <asp:Label Text="Book Pics" runat="server" />
                    </td>
                    <td>
                        <asp:Label ID="Label1" Text="BookName" runat="server" />
                    </td>
                    <td>
                        <asp:Label ID="Label2" Text="Favorite Book" runat="server" />
                    </td>
                </tr>
        </HeaderTemplate>
        <ItemTemplate>
            <tr>
                <td>
                    <asp:Label ID="FavoriteId" Text="0" Visible="false" runat="server" />
                    <asp:Label ID="lblId" Text='<%#Eval("Id") %>' Visible="false" runat="server" />
                    <asp:Image ID="Imagebooks" ImageUrl='<%# "Images/" + Eval("Name") %>' Width="80px"
                        Height="50px" runat="server" />
                </td>
                <td>
                    <asp:Label ID="lblbookName" Text='<%#Eval("Name")%>' runat="server" />
                </td>
                <td>
                    <asp:Button ID="btnAdd" Text="Add" OnClick="OnfavoriteBook" runat="server" />
                </td>
            </tr>
        </ItemTemplate>
        <FooterTemplate>
            </table>
        </FooterTemplate>
    </asp:DataList>
</div>
<br />
<br />
<asp:LinkButton Text="Logout" OnClick="OnLogOut" runat="server" />
</form>

C#

private string constring = ConfigurationManager.ConnectionStrings["constring"].ToString();
protected void Page_Load(object sender, EventArgs e)
{
    if (!this.IsPostBack)
    {
        this.Populatebooks();
    }
}

private void Populatebooks()
{
    string userId = Session["UserId"].ToString();

    using (SqlConnection con = new SqlConnection(constring))
    {

        using (SqlCommand cmd = new SqlCommand("SELECT * FROM [dbo].[Files]", con))
        {
            DataTable dt = new DataTable();
            SqlDataAdapter sda = new SqlDataAdapter(cmd);
            sda.Fill(dt);
            dlBooks.DataSource = dt;
            dlBooks.DataBind();
        }
    }
}

protected void OnfavoriteBook(object sender, EventArgs e)
{
    DataListItem item = (sender as Button).NamingContainer as DataListItem;
    int bookId = Convert.ToInt32((item.FindControl("lblId") as Label).Text);
    int favoriteId = Convert.ToInt32((item.FindControl("FavoriteId") as Label).Text);
    using (SqlConnection con = new SqlConnection(constring))
    {
        if ((item.FindControl("btnAdd") as Button).Text.ToUpper() == "ADD")
        {
            using (SqlCommand cmd = new SqlCommand("INSERT INTO Dim_favorite values(@UserId,@BookId)", con))
            {
                cmd.Parameters.AddWithValue("@UserId", Session["UserId"]);
                cmd.Parameters.AddWithValue("@BookId", bookId);
                con.Open();
                cmd.ExecuteNonQuery();
                con.Close();
            }
        }
        else
        {
            using (SqlCommand cmd = new SqlCommand("DELETE FROM Dim_favorite WHERE FavoriteId=@FavoriteId", con))
            {
                cmd.Parameters.AddWithValue("@FavoriteId", favoriteId);
                con.Open();
                cmd.ExecuteNonQuery();
                con.Close();
            }
        }
    }

    this.Populatebooks();
}
protected void dlBooks_ItemDataBound(object sender, DataListItemEventArgs e)
{
    if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
    {
        string bookid = (e.Item.FindControl("lblId") as Label).Text;

        using (SqlConnection con = new SqlConnection(constring))
        {
            using (SqlCommand cmd = new SqlCommand("SELECT f.Id AS TestId,fav.FavoriteId,f.Name,'Added' [Status] FROM Files f INNER JOIN Dim_favorite fav On f.Id = fav.BookId WHERE fav.UserId='" + Session["UserId"] + "' ", con))
            {
                DataTable dt = new DataTable();
                SqlDataAdapter sda = new SqlDataAdapter(cmd);
                sda.Fill(dt);

                foreach (DataRow row in dt.Rows)
                {
                    if (bookid == row["TestId"].ToString())
                    {
                        (e.Item.FindControl("btnAdd") as Button).Text = "Added";
                        (e.Item.FindControl("FavoriteId") as Label).Text = row["FavoriteId"].ToString();
                    }
                }
            }
        }
    }
}

protected void OnLogOut(object sender, EventArgs e)
{
    Response.Redirect("Login.aspx");
}

Screenshot

I agree, here is the link: https://www.e-iceblue.com/Introduce/spire-office-for-net-free.html