Button inside every product - c#

I am doing a little school project with ASP.NET, and I'm trying to get all products from the Database, show it and have "Add to card" button for every one of them. I managed to do all this, except adding the button. I have a function that gets all the products and I'm binding it with ASP Repeater. The problem is, when I try to add a button, it says that I need to use the form tag first, when I add the form tag it says it needs to have runat="server", but when I add it, it says I can't have more than one runat="server". The Repeater tag is using it also, and I'm stuck. Can anyone suggest something? Thank you!
private void bindPopularProducts()
{
String CS = ConfigurationManager.ConnectionStrings["DatabaseConnectionString1"].ConnectionString;
using (SqlConnection con = new SqlConnection(CS))
{
using (SqlCommand cmd = new SqlCommand("SELECT * FROM Food", con))
{
using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
{
DataTable fFood = new DataTable();
sda.Fill(fFood);
popularFood.DataSource = fFood;
popularFood.DataBind();
}
}
}
}
and this
<asp:Repeater ID="popularFood" runat="server">
<ItemTemplate>
<div class="col-md-4">
<div><%# Eval("name") %></div>
<div><asp:Image ID="foodImage" runat="server" ImageUrl='<%# "~/images/food/" + Eval("image").ToString() %>' Visible="true" CssClass="img-responsive" /></div>
<div>
<div class="col-md-4 text-left"><%# "$"+Eval("price_small")+"/small" %></div>
<div class="col-md-8 text-right">
</div>
</div>
</div>
</ItemTemplate>
</asp:Repeater>
I'm trying to put the button inside the text-right div

Within your Repeater's ItemTemplate, add a button. In the button, set the CommandArgument to some key value that uniquely identifies the product.
<asp:Button ID="Button1" runat="server" Text="Click Me" CommandArgument='<%# Eval("Product.Key") %>' OnClick="Button1_Click" />
In your code, the event handler can use the button's CommandArgument to get the product key and execute your "Add to card" method.
protected void Button1_Click(object sender, EventArgs e)
{
string myProductKey;
// Use "myProductKey" to do something with the Product record...
myProductKey = ((Button)sender).CommandArgument;
}

Related

Why is the textbox in my ASP.NET webform always empty

This is my markup:
<%# Page Title="" Language="C#" MasterPageFile="~/User/Default.Master" AutoEventWireup="true" CodeBehind="Consulation.aspx.cs" Inherits="PetShop.User.Consulation" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">
<script>
window.onload = function () {
var second = 5;
setTimeout(function () {
document.getElementById("<%=lblMsg.ClientID%>").style.display = "none";
}, second * 1000)
}
</script>
<link href="../CSSandJS/StyleCss/consulation.css" rel="stylesheet" />
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
<!-- Slider -->
<section id="Slider">
<div class="aspect-ratio-169">
<img src="../CSSandJS/images/bg_1.jpg" alt="">
<img src="../CSSandJS/images/bg_2.jpg" alt="">
<img src="../CSSandJS/images/bg_3.jpg" alt="">
<img src="../CSSandJS/images/bg_4.jpg" alt="">
</div>
<div class="dot-container">
<div class="dot active"></div>
<div class="dot"></div>
<div class="dot"></div>
<div class="dot"></div>
</div>
</section>
<!-- End Slider -->
<!-- Free Consulation -->
<section class="contact">
<div class="container-contact">
<h1>Đặt lịch hẹn</h1>
<div class="row">
<div class="contact-img">
<img src="../CSSandJS/images/bg_1.jpg" alt="" width="400">
</div>
<div class="input-infor">
<div class="form">
<div class="dbl-field">
<asp:DropDownList ID="ddlCategory" runat="server" CssClass="form-control option field-mail listOp" DataSourceID="SqlDataSource1" DataTextField="TENDV" DataValueField="MADV" AppendDataBoundItems="true">
<asp:ListItem Value="0">Chọn danh mục</asp:ListItem>
</asp:DropDownList>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:cs %>" SelectCommand="SELECT [MADV], [TENDV] FROM [DICHVU]"></asp:SqlDataSource>
</div>
<div class="dbl-field">
<div class="field-mail">
<asp:TextBox ID="txtEmail" runat="server" CssClass="form-control input" placeholder="Nhập email" required></asp:TextBox>
<i class="ri-mail-line"></i>
</div>
</div>
<div class="dbl-field">
<div class="field">
<asp:TextBox ID="txtNameAcc" runat="server" CssClass="form-control input" placeholder="Nhập tên"></asp:TextBox>
<i class="ri-user-line"></i>
</div>
<div class="field">
<asp:TextBox ID="txtSDT" runat="server" CssClass="form-control input" placeholder="Nhập số điện thoại" MaxLength="11"></asp:TextBox>
<i class="ri-phone-line"></i>
</div>
</div>
<div class="dbl-field">
<div class="field">
<asp:TextBox ID="txtNgay" runat="server" CssClass="form-control input" TextMode="Date"></asp:TextBox>
<i class="ri-calendar-2-line"></i>
</div>
<div class="field">
<asp:TextBox ID="txtTime" runat="server" CssClass="form-control input" placeholder="Nhập giờ hẹn" MaxLength="5" TextMode="SingleLine"></asp:TextBox>
<i class="ri-time-line"></i>
</div>
</div>
<div class="message">
<asp:TextBox ID="txtDescription" runat="server" CssClass="form-control textarea" placeholder="Tin nhắn" TextMode="MultiLine"></asp:TextBox>
<i class="ri-message-2-line"></i>
</div>
<div class="button-area">
<asp:Button ID="Add" runat="server" Text="Gửi lịch hẹn" class="btn btn-primary button" OnClick="Add_Click"/>
<asp:Label ID="lblMsg" runat="server" Visible="false"></asp:Label>
<%--<asp:linkbutton id="submitcal" runat="server" cssclass="btn btn-primary button" OnClick="Add_Click">gửi lịch hẹn</asp:linkbutton>--%>
</div>
</div>
</div>
</div>
</div>
</section>
<!-- End Free Consulation -->
</asp:Content>
The textbox doesn't get any value when I debug the program.
I have tested the stored procedure in SQL Server and it works fine. But the data returned from the SQL code is empty.
My button submit code:
namespace PetShop.User
{
public partial class Consulation : System.Web.UI.Page
{
SqlConnection con;
SqlCommand cmd;
protected void Page_Load(object sender, EventArgs e)
{
}
private void clear()
{
txtEmail.Text = string.Empty;
txtDescription.Text = string.Empty;
txtNameAcc.Text = string.Empty;
txtSDT.Text = string.Empty;
txtNgay.Text = string.Empty;
txtTime.Text = string.Empty;
ddlCategory.ClearSelection();
}
protected void Add_Click(object sender, EventArgs e)
{
string actionName = string.Empty;
bool isValidToExcute = true;
con = new SqlConnection(Connection.GetConnectionString());
cmd = new SqlCommand("Add_KHaddLH", con);
cmd.Parameters.AddWithValue("#Action", "INSERT4KH");
cmd.Parameters.AddWithValue("#MaDv", ddlCategory.SelectedValue);
cmd.Parameters.AddWithValue("#EMail", txtEmail.Text.Trim());
cmd.Parameters.AddWithValue("#Ten", txtNameAcc.Text.Trim());
cmd.Parameters.AddWithValue("#Sdt", txtSDT.Text.Trim());
cmd.Parameters.AddWithValue("#NgayHen", txtNgay.Text.ToString());
cmd.Parameters.AddWithValue("#GioHen", txtTime.Text.Trim());
cmd.Parameters.AddWithValue("#GhiC", txtDescription.Text.Trim());
if (isValidToExcute)
{
cmd.CommandType = CommandType.StoredProcedure;
try
{
con.Open();
cmd.ExecuteNonQuery();
actionName = "gửi";
lblMsg.Visible = true;
lblMsg.Text = "Lịch hẹn " + actionName + " thành công!";
lblMsg.CssClass = "alert alert-success";
clear();
}
catch (Exception ex)
{
lblMsg.Visible = true;
lblMsg.Text = "Lỗi !!!" + ex.Message;
lblMsg.CssClass = "alert alert-danger";
}
finally
{
con.Close();
}
}
}
}
}
I think the error lies in the page reload, because when submitting it will delete all the data in the textbox and then enter.
I've tried adding some commands to the button but still can't handle that it keeps losing textbox data.
I update code behind and markup.
Support me,
Thank.
Ok, so that helps a boatload.
if we have this code:
protected void Add_Click(object sender, EventArgs e)
{
string actionName = string.Empty;
bool isValidToExcute = true;
Debug.Print(txtEmail.Text);
output:
So, you might want to put a break point in, or simple add some debug.prints, and see which text box controls are "empty". But, just looking at what you have, those text boxes should be ok.
And including page-load, shows that you not say running the "clear" routine you have. (so, having included the page load event eliminates about 100 possible issues here. This is VERY much why posting some of your code allows the public here to eliminate a 100 "back and forth" suggestions.) So, for example, had you included "clear" routine in page load, then of course page load fires each and every time BEFORE a button click event, so code in page load is VERY OFTEN suspect here. But, since you don't have code in page load event, we scratch that off the table.
So, far, the controls look to have values, but I suggest you add a break point, or some debug.prints as per above to be 100% sure that the controls in fact do not have values.
Also, just pasting in some of the markup, we see things like this:
So, you do have stray "garbage" in a number of places. (not good).
As it stands, with the posted markup, I MOST certainly do get/see/have/enjoy/observe that the text boxes are intact, do have values.
Given we can't re-produce your issue?
I suggest creating a blank new page, drop in some of those controls, and try a test button - (don't even bother with the database save code - we NOT gone that far down the debugging road just yet).
So, only thing so far?
Are you 100% sure the text boxes don't have values, and you tested this BEFORE any of the database save code runs?
and do remove the stray "required" markup in that txtEmail box, the editor even HONKS OUT AT YOU that the markup is bad as per above screen shot.
In fact, drop in another button on the form, and its only job would be to debug print out the text boxes - does that work?
As it stands now, you don't have a re-producable error, and the community in general here has not, does not see your error, nor are we the viewing public EVEN able to re-produce that these text boxes don't have values.
As a result, there information we don't have to re-produce the error.
I suggest building a page with just the txtEmail that is blank, and a simple button. if that works, then start adding markup from that other page until it stops working, since we here can't re-produce your issue with the provided code and markup you have provided.
And, since you using a master page, then check if page load in master page has any code that runs on page load.

Get value of a TextBox inside a DataList

I have a DataList in ASP.NET that brings me the products from the "Products" table, so with the "Eval" statement I assign the product ID:
<asp:TextBox ID="idProductoText" runat="server" type="hidden" value='<%# Eval("PRO_ID") %>'></asp:TextBox>
So in my C# code I need to get the value of that TextBox by its ID, for example an idProductText.Text.Trim(); , but for some reason it doesn't work, any solution? I leave the complete DataList below.
Code to fill the DataList:
public void loadStockProducts()
{
OracleConnection connection = new OracleConnection(with);
OracleCommand command = new OracleCommand("SHOW_PRODUCTS_BUY", connection);
command.CommandType = System.Data.CommandType.StoredProcedure;
command.Parameters.Add("registers", OracleDbType.RefCursor).Direction = ParameterDirection.Output;
OracleDataAdapter d = new OracleDataAdapter();
d.SelectCommand = command;
DataTable dt = new DataTable();
d.Fill(dt);
DataList1.DataSource = dt;
DataList1.DataBind();
connection.Close();
}
Full DataList in ASP.NET
<asp:DataList ID="DataList1" runat="server">
<ItemTemplate>
<div class="card mb-6" style="max-width: 1400px">
<div class="row g-0">
<div class="col-md-4">
<img
src="../../img/armchair.jpg"
class="img-fluid rounded-start"
alt="product" />
</div>
<div class="col-lg-5 m-4 form-floating">
<div class="card-body">
<!-- THE PRODUCT ID IS HIDDEN, IT WILL ONLY BE USED TO ADD TO CART -->
<asp:TextBox ID="idProductoText" runat="server" type="hidden" value='<%# Eval("PRO_ID") %>'></asp:TextBox>
<asp:Label ID="PRO_NAMELabel" class="card-title" runat="server" Text='<%# Eval("PRO_NAME") %>' Font-Bold="true" Font-Size="Large" Visible="True" />
<br />
<br />
Q<asp:Label ID="PRO_PRICELabel" class="card-text" runat="server" Text='<%# Eval("PRO_PRICE") %>' Font-Size="Large" />
<br />
<br />
<div class="input-group">
<asp:Button ID="moreInformation" runat="server" Text="More Information" class="btn btn-dark m-2" />
<asp:TextBox ID="quantidadBuy" runat="server" type="number" class="form-control m-2" placeholder="Quantity to Buy"></asp:TextBox>
<asp:Button ID="addCart" runat="server" Text="Add to Cart" class="btn btn-success m-2"/ OnClick="addCart_Click"/>
</div>
</div>
</div>
</div>
</div>
<br />
</ItemTemplate>
</asp:DataList>
Ok, while there are some events of the data list, you can just grab and get all the information you need/want from that button click you have.
However, before we write that code, I see you need a database row PK id, so, I suggest you remove this:
<!-- THE PRODUCT ID IS HIDDEN, IT WILL ONLY BE USED TO ADD TO CART -->
<asp:TextBox ID="idProductoText" runat="server"
type="hidden" value='<%# Eval("PRO_ID") %>'></asp:TextBox>
Assuming PRO_ID is the PK database id, then we really don't want to have that information in the markup - (even hidden).
So, use the so called "data keys" feature. You COULD leave the above, but remove it - we really don't need it.
So, in datalist, add this setting:
<asp:DataList ID="DataList1" runat="server" DataKeyField = "PRO_ID" >
Ok, so now the click event for the button.
Say we have this button:
<asp:Button ID="cmdView" runat="server" Text="View" CssClass="btn"
OnClick="cmdView_Click" />
Code behind:
protected void cmdView_Click(object sender, EventArgs e)
{
Button cmdView = sender as Button;
DataListItem gRow = cmdView.NamingContainer as DataListItem;
// get row index
Debug.Print("row click = " + gRow.ItemIndex.ToString());
// get database primary key (data keys)
int? PkID = DataList1.DataKeys[gRow.ItemIndex] as int?;
Debug.Print("Database PK id = " + PkID);
// get value of single control - say hotel label called
Label lHotelName = gRow.FindControl("HotelNameLabel") as Label;
Debug.Print("Hotel name = " + lHotelName.Text);
}
Output:
So note several things:
We grab/get current row - naming container. This works for Gridview, repeater, listview - quite much all of the data bound types of controls.
From that row, then we can get:
Row index -
From Row index, we reference into data keys. Note that datalist ONLY supports ONE data key, so in MOST cases, we have to do this .DataKeys[ some index]["SOME KEY"]
But datalist is a exception - only one key, so .DataKeys[some index] is all you require.
And to pull controls out, use .FindControl as I show above.
FYI: debug.print - this requires using System.Diagnostics;
(and I have my outputs re-directed to Immediate window).

How do I get the textbox value to the database within a repeater?

I have a repeater that I populate from a database:
using (SqlConnection conn = new SqlConnection(connString))
{
SqlCommand cmd = new SqlCommand(#"SELECT CommunityName, CID, Budget FROM Donation WHERE Year = year(getdate()) ORDER BY CommunityName", conn);
conn.Open();
SqlDataAdapter adp = new SqlDataAdapter(cmd);
DataSet myDataSet = new DataSet();
adp.Fill(myDataSet);
myRep.ItemDataBound += new RepeaterItemEventHandler(myRep_ItemDataBound);
myRep.DataSource = myDataSet;
myRep.DataBind();
}
void myRep_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
var textbox = e.Item.FindControl("community");
textbox.ClientIDMode = ClientIDMode.Static;
textbox.ID = "community" + (e.Item.ItemIndex + 1);
}
Repeater:
<asp:UpdatePanel ID="UpdatePanel" runat="server" UpdateMode="Always">
<ContentTemplate>
<asp:Repeater ID="myRep" runat="server">
<ItemTemplate>
<div class="form-group">
<asp:Label ID='thisLbl' runat="server" Text='<%# Eval("CommunityName") %>' />
<asp:TextBox runat="server" ID="community" Text='<%# Eval("Budget") %>' CssClass="form-control" />
</div>
</ItemTemplate>
</asp:Repeater>
</ContentTemplate>
</asp:UpdatePanel>
This creates 6 textboxes with labels and values, now my question is how do I detect which of these boxes belongs to the record it was initially pulled from in the database? I want to be able to modify the value in these boxes and hit a button to save them back to the database but I can't seem to wrap my head around getting them to the proper records.
Should I set the ID of the textbox to something I can parse through and match with the proper record? In the ItemDataBound?
You have to put a hidden field inside the repeater item template that takes the value from budget, and another hidden field to keep the CID value that has to be read in the post back request. Of course you need also a button and its click event handler.
<asp:Repeater ID="myRep" runat="server">
<ItemTemplate>
<div class="form-group">
<asp:Label ID='thisLbl' runat="server" Text='<%# Eval("CommunityName") %>' />
<asp:TextBox runat="server" ID="txtBudget" Text='<%# Eval("Budget") %>' CssClass="form-control" />
<asp:HiddenField runat="server" ID="hdOriginalBudget" Value='<%# Eval("Budget") %>' />
<asp:HiddenField runat="server" ID="hdCID" Value='<%# Eval("CID") %>' />
</div>
</ItemTemplate>
</asp:Repeater>
<br />
<asp:Button ID="btn" runat="server" OnClick="btn_Click" />
In your code behind you need to loop inside the repeater to check whether the text box has been changed by comparing its value to the hidden field. After you save the budget value in the database you need to realign the hidden field value to the the new value entered by the user, otherwise you will always save that value after each post back:
protected void btn_Click(object sender, EventArgs e)
{
foreach (RepeaterItem item in myRep.Items)
{
var txtBudget = item.FindControl("txtBudget") as TextBox;
var hdOriginalBudget = item.FindControl("hdOriginalBudget") as HiddenField;
var hdCID = item.FindControl("hdCID") as HiddenField;
if (txtBudget.Text != hdOriginalBudget.Value)
{
//If you enter here means the user changed the value of the text box
using (SqlConnection conn = new SqlConnection(connString))
{
SqlCommand cmd = new SqlCommand(#"UPDATE Donation SET Budget = #Budget WHERE CID = #CID", conn);
cmd.Parameters.Add(new SqlParameter("#Budget", int.Parse(txtBudget.Text)));
cmd.Parameters.Add(new SqlParameter("#CID", int.Parse(hdCID.Value)));
conn.Open();
cmd.ExecuteNonQuery();
}
//After you write in the database realign the values
hdOriginalBudget.Value = txtBudget.Text;
}
}
}
Take care that my code is missing the most basic validation, so if the user writes an invalid value in the textbox (for example "yyy") it breaks. So please don't put it in production as it is!

Update value in ListView

I have a button inside a listview and a label. The label is bound to my database and displays a score. If you press the button I want the score to update on client side. But Since I cant access items in Listview from codebehind I have no idea how to do this. And updatepanel does not work.
My listview bound to a Sqldatasource:
<asp:ListView ID="ListViewSearch" runat="server" DataSourceID="SqlDataSourceWebsite" DataKeyNames="WebsiteID">
My buttons and my label for rating:
<asp:LinkButton ID="BtnUp" runat="server" CssClass="btn btn-default btn-xs" CommandArgument='<%# Eval("testId").ToString() %>' OnClick="up_click"></asp:LinkButton>
<asp:LinkButton ID="BtnDown" runat="server" CssClass="btn btn-default btn-xs" CommandArgument='<%# Eval("testId").ToString() %>' OnCommand="down_click"></asp:LinkButton>
<asp:Label ID="LabelRating" runat="server" Text=' <%# Eval("rating") %>'></asp:Label>
upClick() function:
protected void up_click(object sender, EventArgs e)
{
LinkButton btn = (LinkButton)sender;
String webID = btn.CommandArgument.ToString();
int ID = Convert.ToInt32(webID);
click(ID, 1);
}
Click() function:
public void click(int webID, int vote)
{
using (SqlConnection con = new SqlConnection(strCon))
{
using (SqlCommand cmd = con.CreateCommand())
{
cmd.CommandText = "UPDATE [Test] SET [rating]+=#vote WHERE [testId]=#testID";
cmd.Parameters.AddWithValue("#webID", webID);
cmd.Parameters.AddWithValue("#vote", vote);
con.Open();
cmd.ExecuteNonQuery();
}
con.Close();
}
}
The code updates the rating as it is supposed to, but to see the change I have to refresh the page. So the questions is; How do I update a value inside a listview by clicking a button inside that same lisview?
(If this is not possible, please suggest a different way that I can display results from a search in a list that offers the same customization.)
I'm more into ASP MVC however maybe my tip will help you.
The way I did these behaviors was to bind javascript function to the button and using jQuery I've send 'GET' request to the specific action(method) on the server for example: www.myexample.com/getData?tableid=24 which responds with json containing needed data.
Hope this will direct you to proper solution.
Cheers,
Marek

On link click from menu BindDataList

I have this code:
$(document).ready(function () {
$('#Priroda').hide();
$('#priroda_').click(function () {
$('#Znamenitosti').hide();
$('#Priroda').show();
});
$('#znamenitosti_').click(function () {
$('#Priroda').hide();
$('#Znamenitosti').show();
});
});
</script>
<div class="meni">
<nav>
<ul>
<li class="active">Info</li>
<li>Znamenitosti</li>
<li>Priroda</li>
<li>Noken Zivot</li>
</ul>
</nav>
</div>
where I have few categories in the menu. When i click on specific category, i want to show the (div) tag for that specific category within the same .aspx page, and the other (div) tags for the other categories should be hidden.
This is the (div) tag for the category "Priroda":
<div class="Priroda" id="Priroda">
<asp:DataList ID="DataList1" runat="server" RepeatColumns="7" CellPadding="3">
<ItemTemplate>
<div class="boxButton">
<ul class="Gallery">
<li><a id="A1" href='<%# Eval("ime","~/Sliki/Ohrid/Priroda/{0}") %>' title='<%# "Од "+ Eval("userid")+ ", на " + Eval("datum")+ ", " + Eval("opis")%>' rel="FaceBox[gallery1]" runat="server" >
<asp:Image ID="Image1" ImageUrl='<%# Bind("ime", "~/Sliki/Ohrid/Priroda/{0}") %>' runat="server" Width="140" Height="140" AlternateText='<%# Bind("imeslika") %>' />
</a></li></ul></div>
</ItemTemplate>
</asp:DataList>
</div>
For binding the DataList i used this code in .cs file:
protected void BindDataList1()
{
String strConnString = System.Configuration.ConfigurationManager
.ConnectionStrings["makbazaConnectionString"].ConnectionString;
SqlConnection con = new SqlConnection(strConnString);
con.Open();
//Query to get ImagesName and Description from database
SqlCommand command = new SqlCommand("SELECT ime, imeslika, kategorija, datum, opis, slikapateka, userid FROM Ohrid WHERE kategorija='Priroda'", con);
SqlDataAdapter da = new SqlDataAdapter(command);
DataTable dt = new DataTable();
da.Fill(dt);
dlImages.DataSource = dt;
dlImages.DataBind();
con.Close();
}
Now i don't know how to call BindDataList1(); to show me data when i click on that category. I have different BindDataLists for each category. Can you tell me how to call specific BindDataList for the category that is selected from the menu? For example when i click on link Priroda show me the (div) tag Priroda and BindDalaList1();, when i click on link Znamenitosti show me the (div) tag Znamenitosti and BindDalaList2();
I think a simple way to do this would be to run your databind functions for all categories at once, for example in the PreRender event of "DataList1", so all of the data is on the page, and each bit is just hidden or shown through your jQuery.
Alternatively, could you use instead of tags, and have an OnClick property set to call your DataBind1 method.

Categories