Creating the quantity update button for Cart System in ASP.NET - c#

I am creating the update button for the cart system in asp.net. What am I trying to do is to allow user key in the quantity items and then click the update button. Here is the design of the shopping cart system...
Unfortunately the update button doesn't work properly after the first row. I have debugged the problem and the for loop inside the btn_update_Click method returns the value of zero.
Is there any other way to overcome the problem? Thanks
Here is the source code:
<b><asp:Label ID="lbl_showResult" runat="server" Text=""></asp:Label></b>
<asp:GridView ID="grv_cart" runat="server" AllowPaging="True" AutoGenerateColumns="False" DataSourceID="sds_store" ShowHeader="True" GridLines="None" CssClass="table">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<a class="hyp_productimage imgLiquidFill imgLiquid productImage img-responsive" href='<%# string.Format("product.aspx?ProductID={0}", Eval("product_id")) %>'>
<img src='<%#Eval("image") %>' />
</a>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Product">
<ItemTemplate>
<asp:Hyperlink ID="hyp_productname" Text='<%# Eval("product_name") %>' runat="server" NavigateUrl='<%# string.Format("product.aspx?ProductID={0}", Eval("product_id")) %>'></asp:Hyperlink>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Quantity">
<ItemTemplate>
<asp:TextBox ID="txt_productQuantity" Text='<%# Eval("product_quantity") %>' CssClass="form-control" runat="server" Width="60" MaxLength="5"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:Button ID="btn_update" Text="Update" runat="server" CommandArgument='<%# Eval("id") %>' CssClass="btn btn-warning" OnClick="btn_update_Click" />
<asp:Button ID="btn_remove" Text="Delete" runat="server" CommandArgument='<%# Eval("id") %>' CssClass="btn btn-danger" onclick="btn_remove_Click"/>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Cost">
<ItemTemplate>
<asp:Hyperlink ID="hyp_productcost" Text='<%#"$"+Eval("product_cost") %>' runat="server" NavigateUrl='<%# string.Format("product.aspx?ProductID={0}", Eval("product_id")) %>'></asp:Hyperlink>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="sds_store" runat="server"
ConnectionString="<%$ ConnectionStrings:websiteConnection %>"
SelectCommand="SELECT [id], [product_id], [product_name], [product_cost], [product_description], [product_quantity], [image], [date] FROM [tbl_cart] WHERE [name] = #username AND [visible] = #visible">
<SelectParameters>
<asp:sessionparameter sessionfield="login" Name="username" />
<asp:Parameter Name="visible" Type="string" DefaultValue="true" />
</SelectParameters>
</asp:SqlDataSource>
<h4><asp:Label ID="lbl_totalCost" Text="" runat="server" CssClass="pull-right"></asp:Label></h4>
<br /><br /><br />
<asp:Button ID="btn_buy" Text="Buy Now" runat="server" CssClass="btn btn-success btn-lg pull-right" OnClick="btn_buy_Click" />
Here's another source code for the .cs:
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data.SqlClient;
using System.Diagnostics;
using System.Linq;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace websiteEcom
{
public partial class cart : System.Web.UI.Page
{
// Open the connection for the sql
private static SqlConnection conn;
private static SqlCommand command;
protected void Page_Load(object sender, EventArgs e)
{
// Create an instance for the connection of database
string connectionString = ConfigurationManager.ConnectionStrings["websiteConnection"].ToString();
conn = new SqlConnection(connectionString);
command = new SqlCommand("", conn);
// Checks how many items are there inside the cart database and display it to the label
CheckHowManyItem();
// Multiply all the sums of the cost
lbl_totalCost.Text = "Total Cost: $"+TotalProductCost().ToString();
}
// Checks how many items are there inside the cart database and display it to the label
public void CheckHowManyItem()
{
try
{
conn.Open();
// Retrieve the number of rows from the database
string query = string.Format("SELECT COUNT(*) FROM tbl_cart WHERE name = '{0}' AND visible = '{1}'", Session["login"], "true");
command.CommandText = query;
int numberOfItems = (int)command.ExecuteScalar();
// If the number of rows is zero
if (numberOfItems == 0)
{
lbl_showResult.Text = "You have no items inside the cart.";
btn_buy.Visible = false;
}
else
{
// If there is number of rows inside
lbl_showResult.Text = "There are currently " + numberOfItems + " inside the cart.";
btn_buy.Visible = true;
}
}
finally
{
conn.Close();
}
}
protected void btn_remove_Click(object sender, EventArgs e)
{
// Get the value from the button ASP.NET gridview
Button btn = (Button)sender;
try
{
conn.Open();
// Make the cart invisible if the id matches with the grid view data source
string query = string.Format("UPDATE tbl_cart SET visible = '{0}' WHERE id = '{1}'", "false", btn.CommandArgument);
command.CommandText = query;
command.ExecuteNonQuery();
Response.Redirect("cart.aspx");
}
finally
{
conn.Close();
}
}
// Multiply all the values of purchases together
public int TotalProductCost()
{
int totalCost = 0;
int currentCost = 0;
int currentQuantity = 0;
for (int i = 0; i < grv_cart.Rows.Count; i++)
{
// Get the data values from the forms
HyperLink hypCost = (HyperLink)grv_cart.Rows[i].Cells[0].FindControl("hyp_productcost");
TextBox txtQuantity = (TextBox)grv_cart.Rows[i].Cells[0].FindControl("txt_productQuantity");
// Sum the product quantity and the product cost
// Attempt to parse your value (removing any non-numeric values)
currentQuantity = Int32.Parse(Regex.Replace(txtQuantity.Text, #"[^\d]", ""));
// Attempt to parse your value (removing any non-numeric values)
currentCost = Int32.Parse(Regex.Replace(hypCost.Text, #"[^\d]", ""));
currentCost *= currentQuantity;
totalCost += currentCost;
}
return totalCost;
}
protected void btn_buy_Click(object sender, EventArgs e)
{
}
protected void btn_update_Click(object sender, EventArgs e)
{
// Get the value from the button ASP.NET gridview
Button btn = (Button)sender;
foreach (GridViewRow grvCart in grv_cart.Rows)
{
Debug.WriteLine(btn.CommandArgument);
TextBox textQuantity = (TextBox)grvCart.FindControl("txt_productQuantity");
int currentQuantity = Int32.Parse(Regex.Replace(textQuantity.Text, #"[^\d]", ""));
try
{
conn.Open();
// Update the cart quantity if the id matches with the grid view data source
string query = string.Format("UPDATE tbl_cart SET product_quantity = '{0}' WHERE id = '{1}'", currentQuantity, btn.CommandArgument);
command.CommandText = query;
command.ExecuteNonQuery();
Response.Redirect("cart.aspx");
}
finally
{
conn.Close();
}
}
}
}
}

Try using the RowCommand event (especially since you already have the CommandArgument set up). That is the more appropriate way to handle this type of action (and that way you can just update one row at a time, without looping through all of them).
Handle the RowCommand event in your GridView declaration:
<asp:GridView ID="grv_cart" runat="server" AllowPaging="True"
AutoGenerateColumns="False" DataSourceID="sds_store" ShowHeader="True"
GridLines="None" CssClass="table" OnRowCommand="grv_cart_RowCommand">
And then your event handler would look like this:
protected void grv_cart_RowCommand(Object sender, GridViewCommandEventArgs e)
{
GridViewRow rowToUpdate = grv_cart.Rows[Int.Parse(e.CommandArgument)];
TextBox textQuantity = (TextBox)rowToUpdate.FindControl("txt_productQuantity");
int currentQuantity = Int32.Parse(Regex.Replace(textQuantity.Text, #"[^\d]", ""));
try
{
conn.Open();
// Update the cart quantity if the id matches with the grid view data source
string query = string.Format("UPDATE tbl_cart SET product_quantity = '{0}' WHERE id = '{1}'", currentQuantity, e.CommandArgument);
command.CommandText = query;
command.ExecuteNonQuery();
Response.Redirect("cart.aspx");
}
finally
{
conn.Close();
}
}
Note: You'll want to remove the OnClick handler from the update button:
<asp:Button ID="btn_update" Text="Update" runat="server"
CommandArgument='<%# Eval("id") %>' CssClass="btn btn-warning" />

Related

event handling is not working in my asp.net web forms web application

The update button Onclick event is not working.
I inserted one more button called button1 for testing if it works, but found that it is not working, even Icacked in other web forms in the app
It is not working at all.
Only page load event-driven is working.
Update:
The problem is not solved with other controls. For example, after the user clicks on an update button, a fucntion will be called that checks the value in the textbox and make some calculation.
After debugging, I found that the program cannot read any values from the textbox.
Note: I am using packages like bootstrap, Ajax as they are already built-in in the asp.net web forms web applications. I have also tried to exclude them from the project as mentioned in some references, however, nothing changed.
Here is my code for Shopping Cart web form:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Celebreno.Models;
using Celebreno.Cart;
//to use IOrderedDictionary
using System.Collections.Specialized;
using System.Collections;
using System.Web.ModelBinding;
namespace Celebreno
{
public partial class ShowCart : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
//2- Display the total of cart by calling GetTotal() function(located in Actions_of_Cart class)
//and then store the return value in a new variable, then dispaly it in a label
using (Actions_of_Cart usersShoppingCart = new Actions_of_Cart())
{
//declare a new variable to store the total into it
decimal cartTotal = 0;
cartTotal = usersShoppingCart.GetTotal();
if (cartTotal > 0)
{
//Display Total in a label that has property " Enable ViewState = False"
// ViewSate used
LblTotal.Text = String.Format("{0:c}", cartTotal);
}
else
{
LblTotalText.Text = "";
LblTotal.Text = "";
//HtmlGenericControl
ShoppingCartTitle.InnerText = "The Shopping Cart is Empty";
//not yet needed
UpdateBtn.Visible = false;
// CheckoutImageBtn.Visible = false;
}
Button1.Click += Button1_Click;
}
}
//1- decalre the "select Method" (used in GridView in Source Code) to return the value of..
//..calling GetCartItems(), which is defined in Actions_of_Cart DB class
public List<ItemsInCart> GetShoppingCartItems()
{
Actions_of_Cart actions = new Actions_of_Cart();
return actions.GetCartItems();
}
//
public List<ItemsInCart> UpdateCartItems()
{
using (Actions_of_Cart usersShoppingCart = new Actions_of_Cart())
{
//new var
String cartId = usersShoppingCart.GetCartId();
//The UpdateCartItems method gets the updated values for each item in the shopping cart.
//Then, the UpdateCartItems method calls the UpdateShoppingCartDatabase method
//to either add or remove items from the shopping cart.
//Once the database has been updated to reflect the updates to the shopping cart,
//the GridView control is updated on the shopping cart page by calling the DataBind method
//for the GridView. Also, the total order amount on the shopping cart page is updated
//to reflect the updated list of items.
Actions_of_Cart.ShoppingCartUpdates[] cartUpdates = new Actions_of_Cart.ShoppingCartUpdates[CartList.Rows.Count];
for (int i = 0; i < CartList.Rows.Count; i++)
{
IOrderedDictionary rowValues = new OrderedDictionary();
rowValues = GetValues(CartList.Rows[i]);
//ProductId related to struct in Actions
cartUpdates[i].ProductId = Convert.ToInt32(rowValues["ID"]);
CheckBox cbRemove = new CheckBox();
cbRemove = (CheckBox)CartList.Rows[i].FindControl("RemoveItem");
cartUpdates[i].RemoveItem = cbRemove.Checked;
TextBox quantityTextBox = new TextBox();
quantityTextBox = (TextBox)CartList.Rows[i].FindControl("PurchaseQuantity");
cartUpdates[i].PurchaseQuantity = Convert.ToInt16(quantityTextBox.Text.ToString());
}
usersShoppingCart.UpdateShoppingCartDatabase(cartId, cartUpdates);
CartList.DataBind();
//dispaly updated total value
LblTotal.Text = String.Format("{0:c}", usersShoppingCart.GetTotal());
return usersShoppingCart.GetCartItems();
}
}
public static IOrderedDictionary GetValues(GridViewRow row)
{
try
{
IOrderedDictionary values = new OrderedDictionary();
foreach (DataControlFieldCell cell in row.Cells)
{
if (cell.Visible)
{
// Extract values from the cell.
cell.ContainingField.ExtractValuesFromCell(values, cell, row.RowState, true);
}
}
return values;
}
catch (Exception exp)
{
throw new Exception("ERROR1" + exp.Message.ToString(), exp);
}
}
protected void UpdateBtn_Click(object sender, EventArgs e)
{
UpdateCartItems();
}
protected void Button1_Click(object sender, EventArgs e)
{
Label1.Text = "IT is working ";
}
}
}
Source Code:
<%# Page Title="" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="ShowCart.aspx.cs" Inherits="Celebreno.ShowCart" %>
<asp:Content ID="Content1" ContentPlaceHolderID="MainContent" runat="server">
<div id="ShoppingCartTitle" runat="server" class="ContentHead"><h1>Shopping Cart</h1></div>
<%--Start of the GridView to display the items in the cart--%>
<asp:GridView ID="CartList" runat="server" AutoGenerateColumns="False" ShowFooter="True" GridLines="Vertical" CellPadding="4"
ItemType="Celebreno.Models.ItemsInCart" SelectMethod="GetShoppingCartItems"
CssClass="table table-striped table-bordered" >
<Columns>
<%--problem solved : change "ID" to "ServicePack.ID"--%>
<asp:BoundField DataField="ServicePack.ID" HeaderText="Service Package ID" SortExpression="ID" />
<asp:BoundField DataField="ServicePack.Provider" HeaderText="Provider" />
<asp:BoundField DataField="ServicePack.UnitPrice" HeaderText="Price (each)" DataFormatString="{0:c}"/>
<asp:TemplateField HeaderText="Quantity">
<ItemTemplate>
<asp:TextBox ID="PurchaseQuantity" Width="40" runat="server" Text="<%#: Item.Quantity %>"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Item Total">
<ItemTemplate>
<%#: String.Format("{0:c}", ((Convert.ToDouble(Item.Quantity)) * Convert.ToDouble(Item.ServicePack.UnitPrice)))%>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Remove Item">
<ItemTemplate>
<%--checkbox for removing the item--%>
<asp:CheckBox id="Remove" runat="server"></asp:CheckBox>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<%--End of the GridView--%>
<div>
<p></p>
<strong>
<%--2 (display the total of the cart--%>
<asp:Label ID="LblTotalText" runat="server" Text="Order Total: "></asp:Label>
<asp:Label ID="LblTotal" runat="server" EnableViewState="false"></asp:Label>
</strong>
</div>
<br />
<table>
<tr>
<td>
<%--3 ( add update button) --%>
</td>
<td>
<asp:Button ID="UpdateBtn" runat="server" Text="Button" OnClick="UpdateBtn_Click" />
<asp:Button ID="Button1" runat="server" Text="Test" OnClick="Button1_Click" />
<asp:Label ID="Label1" runat="server" Text="Test"></asp:Label>
</td>
</tr>
</table>
</asp:Content>
solved : by adding two attributes as shown below
<asp:Button ID="UpdateBtn" runat="server" OnClick="UpdateBtn_Click" Text="Button" CausesValidation="False" UseSubmitBehavior="false" />

How to get selected each radio button value in datalist?

In below datalist represents set of question's and answer.
How to insert the user selected right answer radio button value into database when the user clicks on Final submit button?
<asp:DataList ID="DataList1" runat="server" DataSourceID="AccessDataSource1" BackColor="White" BorderColor="#E7E7FF" BorderStyle="None" BorderWidth="1px" CellPadding="3" GridLines="Horizontal" onselectedindexchanged="rd_CS_CheckedChanged">
<FooterStyle BackColor="#B5C7DE" ForeColor="#4A3C8C" />
<AlternatingItemStyle BackColor="#F7F7F7" />
<ItemStyle BackColor="#E7E7FF" ForeColor="#4A3C8C" />
<SelectedItemStyle BackColor="#738A9C" Font-Bold="True" ForeColor="#F7F7F7" />
<HeaderStyle BackColor="#4A3C8C" Font-Bold="True" ForeColor="#F7F7F7" />
<ItemTemplate>
Q:
<asp:Label ID="QLabel" runat="server" Text='<%# Eval("Q") %>' />
<br />
A:
<asp:RadioButton ID="rd_CS" runat="server" GroupName="Casi" OnCheckedChanged="rd_CS_CheckedChanged" Text='<%# Eval("A") %>'></asp:RadioButton>
<br />
B:
<asp:RadioButton ID="rd_CS2" runat="server" GroupName="Casi" OnCheckedChanged="rd_CS_CheckedChanged" Text='<%# Eval("B") %>'></asp:RadioButton>
<br />
C:
<asp:RadioButton ID="rd_CS3" runat="server" GroupName="Casi" OnCheckedChanged="rd_CS_CheckedChanged" Text='<%# Eval("C") %>'></asp:RadioButton>
<br />
D:
<asp:RadioButton ID="rd_CS4" runat="server" GroupName="Casi" OnCheckedChanged="rd_CS_CheckedChanged" Text='<%# Eval("D") %>'></asp:RadioButton>
<p style="color: #FF3300">
<asp:Label ID="Correct_AnswerLabel" runat="server"
Text='<%# Eval("Correct_Answer") %>' Visible="False" /></p>
</ItemTemplate>
<SelectedItemStyle BackColor="#FFCC66" Font-Bold="True" ForeColor="#663399" />
</asp:DataList>
<asp:AccessDataSource ID="AccessDataSource1" runat="server"
DataFile="~/App_Data/Quize.mdb"
SelectCommand="SELECT [Q],[A], [B], [C], [D], [Correct Answer] AS Correct_Answer FROM [QuizData]">
</asp:AccessDataSource>
<asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Button" />
In Button1_Click on your codebehind you can improve this method:
protected void Button1_Click(object sender, EventArgs e)
{
foreach (DataListItem item in DataList1.Items)
{
RadioButton rd_CS = (RadioButton)item.FindControl("rd_CS");
RadioButton rd_CS2 = (RadioButton)item.FindControl("rd_CS2");
RadioButton rd_CS3 = (RadioButton)item.FindControl("rd_CS3");
RadioButton rd_CS4 = (RadioButton)item.FindControl("rd_CS4");
if (rd_CS.Checked)
{
Insert(rd_CS.Text); //Here you can insert whatever value you want, I tried with Text of radiobutton
}
if (rd_CS2.Checked)
{
Insert(rd_CS2.Text); //Here you can insert whatever value you want, I tried with Text of radiobutton
}
if (rd_CS3.Checked)
{
Insert(rd_CS3.Text); //Here you can insert whatever value you want, I tried with Text of radiobutton
}
if (rd_CS4.Checked)
{
Insert(rd_CS4.Text); //Here you can insert whatever value you want, I tried with Text of radiobutton
}
}
}
And the Insert function definition will be same as:
private void Insert(string value)
{
//Your code here to save on database
OleDbConnection connection = new OleDbCommand("Your sql connection String");
OleDbCommand command = new OleDbCommand("Your sql insert query");
command.Connection = connection;
//Parámeters of command
OleDbParameter param = new OleDbParameter("Parameter name and next your type", OleDbType.VarChar);
param.Value = value;
command.Parameters.Add(param);
command.Connection.Open();
command.ExecuteNonQuery();
command.Connection.Close();
//Your value is saved now
}
This is how you can save all checked radiobutton on datalist you asked
This is my codebehind .When i click on button then Repeated selected radio button values are save in my database . this is my problem. I need only unique value in my database
protected void rd_CS_CheckedChanged(object sender, EventArgs e)
{
string myRadioText = String.Empty;
foreach (DataListItem item in DataList1.Items)
{
RadioButton rd_CS = (RadioButton)item.FindControl("rd_CS");
RadioButton rd_CS2 = (RadioButton)item.FindControl("rd_CS2");
RadioButton rd_CS3 = (RadioButton)item.FindControl("rd_CS3");
RadioButton rd_CS4 = (RadioButton)item.FindControl("rd_CS4");
if (rd_CS != null && rd_CS.Checked)
{
myRadioText = rd_CS.Text;
Label1.Text = myRadioText.ToString();
}
else if (rd_CS2 != null && rd_CS2.Checked)
{
myRadioText = rd_CS2.Text;
Label1.Text = myRadioText.ToString();
}
else if (rd_CS3 != null && rd_CS3.Checked)
{
myRadioText = rd_CS3.Text;
Label1.Text = myRadioText.ToString();
}
else if (rd_CS4 != null && rd_CS4.Checked)
{
myRadioText = rd_CS4.Text;
Label1.Text = myRadioText.ToString();
}
string str = Server.MapPath("~/App_Data/Quize.mdb");
OleDbConnection ole = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + str + ";Persist Security Info=True");
ole.Open();
OleDbCommand cmd = new OleDbCommand("insert into Userdata values ('" + Label1.Text.Trim().Replace("'", "''") + "','" + Label1.Text.Trim().Replace("'", "''") + "',)", ole);
cmd.ExecuteNonQuery();
}

gridview can't add after clearing

I am using entity framework and taking my datas from database and fill my gridview with them.Datas selected by user from a treview.Simply, user selects a data from treeview and I put it to gridview. Lastly I have a button for clearing the gridview. Here is my aspx:
<div id="divPrint" style="background-color: white" runat="server">
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<p style="text-align:center">HDCVI KAMERA FİYAT TEKLİFİDİR</p>
<asp:GridView ID="GridViewHdcvi" runat="server" DataSourceID="EntityDataSourceHdcvi" AutoGenerateColumns="False">
<Columns>
<asp:TemplateField HeaderText="ÜRÜN VE DETAYLARI">
<ItemStyle Width="400px" />
<ItemTemplate>
<div style="color: red" class="text-center"><%#Eval("UrunAdi") %></div>
<%#Eval("UrunDetay") %>
</ItemTemplate>
</asp:TemplateField>
<asp:ImageField HeaderText="ÜRÜN GÖRSELİ" DataImageUrlField="UrunResim"></asp:ImageField>
<asp:TemplateField HeaderText="BİRİM FİYAT">
<ItemTemplate>
<%#Eval("UrunFiyati") %>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="ADET">
<ItemTemplate>
<asp:TextBox ID="txtAdet" runat="server" Width="40px"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</ContentTemplate>
</asp:UpdatePanel>
</div>
<asp:Button ID="btnListiSifirla" runat="server" Text="Listeyi Sıfırla" CssClass="btn btn-danger" OnClick="btnListiSifirla_Click" />
And my codebehind:
static List<string> urunList = new List<string>();
protected void TreeView1_SelectedNodeChanged(object sender, EventArgs e)
{
string id = TreeView1.SelectedValue;
urunList.Add(id);
listeyiDoldur();
}
protected void listeyiDoldur()
{
if (urunList.Count == 0)
{
failDiv.Visible = true;
}
else
{
string query = "SELECT UrunTable.UrunAdi, UrunTable.UrunFiyati, UrunTable.UrunResim, UrunTable.UrunKategori, UrunTable.UrunDetay FROM UrunTable WHERE ";
foreach (var val in urunList)
{
if (val.Equals(urunList[urunList.Count - 1]))
{
query += "UrunTable.UrunId = " + val;
}
else
{
query += "UrunTable.UrunId = " + val + " || ";
}
}
EntityDataSourceHdcvi.CommandText = query;
divPrint.Visible = true;
btnListiSifirla.Visible = true;
}
}
protected void btnListiSifirla_Click(object sender, EventArgs e)
{
urunList.Clear();
btnListiSifirla.Visible = false;
Page_Load(null,EventArgs.Empty);
}
I can successfully display selected datas in gridview and clear them when button is pressed. Here is the problem: After clearing the gridview I can't add the last added item again.For example if I add item1,item2 and item3 in this order,after clearing the gridview I can't add item3. I can add item1 or item2, then item3. I can't add item firstly which I added last before clearing. I tried clearing gridview in button's onClick and tried other lots of things but nothing gave any result. Thanks for your time.

fileupload control only uploading 1 file

I am trying to make the upload control upload multiple files, but it is only uploading one and I am not sure why. Also I want to call the stored proc if, and only if, all required files have successfully been uploaded. Any suggestions would be helpful as I am at a loss. im sure its something im doing wrong within my foreach loop but I am unsure what exactly it is.
My markup:
<%# Page Title="" Language="C#" MasterPageFile="~/Admin/AdminMaster.master" AutoEventWireup="true" CodeFile="addFont.aspx.cs" Inherits="Admin_addFont" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="Server"></asp:Content>
<asp:Content ID="Content3" ContentPlaceHolderID="RightCol" runat="Server">
<h1>Fonts</h1>
<h2>Currently available fonts</h2>
<div><asp:Label ID="lblFontGrd" runat="server"></asp:Label>
<asp:GridView ID="grdFonts" runat="server" CellPadding="4" ForeColor="#333333" GridLines="None" AutoGenerateColumns="False"
OnPageIndexChanging="grdFonts_PageIndexChanging">
<AlternatingRowStyle BackColor="White" ForeColor="#284775"></AlternatingRowStyle>
<Columns>
<asp:TemplateField AccessibleHeaderText="ID" FooterText="ID" HeaderText="ID">
<ItemTemplate>
<asp:Label ID="fontId" runat="server" Text='<%# Eval("FontId") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField AccessibleHeaderText="Font Name" FooterText="Font Name" HeaderText="Font Name">
<ItemTemplate>
<asp:Label ID="lblfontName" runat="server" Text='<%# Eval("FontName") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:Label ID="lblfontNameEdit" runat="server" Text='<%# Eval("FontName") %>'></asp:Label>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField AccessibleHeaderText="Example" FooterText="Example" HeaderText="Example">
<ItemTemplate>
<asp:Label id="lblfontExample" runat="server" Font-Size="Large" Font-Names='<%# BuildFont(Eval("FontFamily").ToString()) %>' ><h3>This is an example of the font</h3></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField AccessibleHeaderText="Discontinued?" HeaderText="Discontinued?" FooterText="Discontinued?">
<ItemTemplate>
<asp:CheckBox ID="Discontinued" runat="server" Checked='<%# Eval("Discontinued") %>' Enabled="false" />
</ItemTemplate>
<EditItemTemplate>
<asp:CheckBox ID="Discontinued" runat="server" Checked='<%# Eval("Discontinued") %>' Enabled="true" />
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Edit">
<ItemTemplate>
<span onclick="return confirm('Are you sure you want to delete?')">
<asp:LinkButton ID="btnDelete" Text="Delete" runat="server" CommandName="Delete" />
</span>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<EditRowStyle BackColor="#999999"></EditRowStyle>
<FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White"></FooterStyle>
<HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White"></HeaderStyle>
<PagerStyle HorizontalAlign="Center" BackColor="#284775" ForeColor="White"></PagerStyle>
<RowStyle BackColor="#F7F6F3" ForeColor="#333333"></RowStyle>
<SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333"></SelectedRowStyle>
<SortedAscendingCellStyle BackColor="#E9E7E2"></SortedAscendingCellStyle>
<SortedAscendingHeaderStyle BackColor="#506C8C"></SortedAscendingHeaderStyle>
<SortedDescendingCellStyle BackColor="#FFFDF8"></SortedDescendingCellStyle>
<SortedDescendingHeaderStyle BackColor="#6F8DAE"></SortedDescendingHeaderStyle>
</asp:GridView>
</div>
<div>
<h2>Add a new font</h2>
<asp:Label ID="lblUpload" runat="server" ForeColor="Red"></asp:Label>
<p>In order to add a new font to the library please follow the steps laid out below:</p>
<p><strong>Step 1: </strong> The first, and most important, thing to do is make sure you have the appropriate license to use your font for print and web.</p>
<p><strong>Step 2: </strong> Next you need to convert your font file into multple formats to ensure browser compatability.
To do so please follow <a target="_blank" href="http://www.fontsquirrel.com/tools/webfont-generator">this</a> link.
Select OPTIMAL and upload your file. Unzip the files generated by the tool.</p>
<p><strong>Step 3: </strong> Now you need open the file that ends with '.css', a simple text editor such as notepad will do just fine.</p>
<p><strong>Step 4: </strong> Find the font-family property(see image below)</p><br />
<asp:Image ID="imgFontCssEx" runat="server" ImageUrl="~/Images/fontCssImg.png" /><br />
<p><strong>Step 5: </strong> Make sure you copy the font-family value exactly as shown in the css into the text box below, marked Font Name.</p>
<asp:TextBox ID="txtFontFam" runat="server"></asp:TextBox>
<asp:Label ID="lblFontFam" runat="server" Text="Font Family"></asp:Label>
<br />
<p><strong>Step 6: </strong> Enter a display name for your font.</p>
<asp:TextBox ID="txtFontName" runat="server"></asp:TextBox>
<asp:Label ID="lblFontName" runat="server" Text="Display Name" ></asp:Label>
<br />
<p><strong>Step 7: </strong> Now you need to upload the files specified below:</p><br />
<asp:FileUpload ID="flupFonts" runat="server" AllowMultiple="true" />
<asp:Label ID="lblCss" runat="server" AssociatedControlID="flupFonts" Text="Upload file with files ending: .css, .ttf, .svg, .eot, .woff, .woff2"></asp:Label>
<p><strong>Finally:&nbsp</strong> Click the button below and the font will be made available.</p>
<br />
<asp:Button ID="btnUploadFont" runat="server" Text="Add Font" OnClick="btnUploadFont_Click" />
</div>
My code behind:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Drawing;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlTypes;
using System.Data.SqlClient;
using System.Web.Configuration;
using System.IO;
using System.Data;
public partial class Admin_addFont : System.Web.UI.Page
{
private string fontUploadDirectory;
private string connectionString =
WebConfigurationManager.ConnectionStrings["bncConn"].ConnectionString;
protected void Page_Load(object sender, EventArgs e)
{
// ensure files are uploaded to the right folder
fontUploadDirectory = Server.MapPath(#"~\fonts\");
if (!this.IsPostBack)
{
BindGrid();
}
}
protected void BindGrid()
{
// define ado.net objects
SqlConnection con = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand("ProductDetails.bnc_Fonts", con);
cmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
// define parameters
cmd.Parameters.Add(new SqlParameter("#status", SqlDbType.VarChar, 50));
cmd.Parameters["#status"].Value = "Display";
// attempt to connect to db, read data, fill dataset and bind gridview. Catch exceptions and close the connection.
try
{
con.Open();
DataSet ds = new DataSet();
adapter.Fill(ds, "Fonts");
grdFonts.DataSource = ds;
grdFonts.DataBind();
}
catch (Exception err)
{
lblFontGrd.Text = err.Message;
}
finally
{
con.Close();
}
}
protected void grdFonts_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
grdFonts.PageIndex = e.NewPageIndex;
BindGrid();
}
public static string[] BuildFont(string font)
{
string[] array = new string[1];
array[0] = font;
return array;
}
protected void btnUploadFont_Click(object sender, EventArgs e)
{
string[] validFileTypes = { "eot", "ttf", "svg", "woff", "woff2", "css" };
bool isValidFile = false;
// check files are being submitted
if (flupFonts.HasFiles == false)
{
lblUpload.Text = "No files have been selected.";
}
else
{
HttpFileCollection fileCollection = Request.Files;
if (fileCollection.Count == 6)
{
string serverFileName = Path.GetFileName(flupFonts.PostedFile.FileName);
string ext = Path.GetExtension(serverFileName).ToLower();
string fullUploadPath = Path.Combine(fontUploadDirectory, serverFileName);
try {
foreach (HttpPostedFile uploadedFont in flupFonts.PostedFiles)
{
for (int i = 0; i < validFileTypes.Length; i++)
{
if (ext == "." + validFileTypes[i])
{
isValidFile = true;
if (!File.Exists(fullUploadPath))
{
try
{
flupFonts.PostedFile.SaveAs(fullUploadPath);
break;
}
catch (Exception err)
{
lblUpload.Text = err.Message;
}
}
}
}
if (!isValidFile)
{
lblUpload.Text += "Invalid File. Please upload a File with extension " + string.Join(",", validFileTypes);
}
}
fontDbInfo();
BindGrid();
}
catch (Exception err)
{
lblUpload.Text = "Error: " + err.Message;
}
}
else
{
if (fileCollection.Count < 6)
{
lblUpload.Text = "Please make sure you select all required files.";
}
if (fileCollection.Count > 6)
{
lblUpload.Text = "You have selected too many files. Please only add the required files.";
}
}
}
}
protected void fontDbInfo()
{
// define ado.net objects
SqlConnection con = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand("ProductDetails.bnc_Fonts", con);
cmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
// define sp parameters
cmd.Parameters.Add(new SqlParameter("#Status", SqlDbType.VarChar, 50));
cmd.Parameters["#Status"].Value = "Add";
cmd.Parameters.Add(new SqlParameter("#FontName", SqlDbType.VarChar, 50));
cmd.Parameters["#FontName"].Value = txtFontName.Text;
cmd.Parameters.Add(new SqlParameter("#FontFamily", SqlDbType.VarChar, 50));
cmd.Parameters["#FontFamily"].Value = txtFontFam.Text;
cmd.Parameters.Add(new SqlParameter("#Discontinued", SqlDbType.Bit));
cmd.Parameters["#Discontinued"].Value = 0;
// try to open database, insert font info, catch errors and close the connection
try
{
con.Open();
cmd.ExecuteNonQuery();
DataSet ds = new DataSet();
adapter.Fill(ds, "Fonts");
}
catch (Exception err)
{
lblFontGrd.Text = "Error: " + err.Message;
}
finally
{
con.Close();
}
}}
my stored procedure:
CREATE PROCEDURE [ProductDetails].[bnc_Fonts]
-- Add the parameters for the stored procedure here
#Status varchar(50) = '',
#FontId tinyint = '',
#FontName varchar(50) = '',
#FontFamily varchar(50) = '',
#Discontinued bit = ''
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
if (#Status = 'Display')
begin
select FontId, FontName, FontFamily, Discontinued
from ProductDetails.Fonts
where Discontinued = 0
order by FontName asc
end
if (#Status = 'FontFam')
begin
select FontFamily from ProductDetails.Fonts
where FontId = #FontId
end
if (#Status = 'Add')
begin
insert into ProductDetails.Fonts (FontName, FontFamily, Discontinued)
values (#FontName, #FontFamily, #Discontinued)
end
if (#Status = 'Delete')
begin
UPDATE ProductDetails.Fonts
SET Discontinued = #Discontinued
where FontId = #FontId
end
END
I think the way you are attempting to loop through the HttpPostedFile collection is causing you problems. Try checking file validity in a separate method. I'd also suggest you break this problem down into pieces you can test. For example, try a simple Test page with code something like this. Hope this helps.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Drawing;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlTypes;
using System.Data.SqlClient;
using System.Web.Configuration;
using System.IO;
using System.Data;
public partial class Test : System.Web.UI.Page
{
private string fontUploadDirectory;
protected void Page_Load(object sender, EventArgs e)
{
// ensure files are uploaded to the right folder
fontUploadDirectory = Server.MapPath(#"~\fonts\");
}
protected void btnUploadFont_Click(object sender, EventArgs e)
{
string[] validFileTypes = { ".eot", ".ttf", ".svg", ".woff", ".woff2", ".css" };
// check files are being submitted
if (flupFonts.HasFiles == false)
{
lblUpload.Text = "No files have been selected.";
}
else
{
HttpFileCollection fileCollection = Request.Files;
foreach (HttpPostedFile uploadedFont in flupFonts.PostedFiles)
{
string ext = System.IO.Path.GetExtension(uploadedFont.FileName);
if (isValid(uploadedFont, validFileTypes, ext))
{
uploadedFont.SaveAs(fontUploadDirectory + "\\" + System.IO.Path.GetFileName(uploadedFont.FileName));
}
}
}
}
private bool isValid(HttpPostedFile file, string[] extAry, string ext)
{
bool isValid = false;
for (int i = 0; i < extAry.Length; i++)
{
if (ext.ToLowerInvariant().IndexOf(extAry[i]) > -1)
isValid = true;
}
return isValid;
}
}
Replace this loop:
foreach (HttpPostedFile uploadedFont in flupFonts.PostedFiles)
{
...
}
With this:
foreach(string key in flupFonts.Keys)
{
HttpPostedFile uploadedFont = flupFonts[key];
...
}

I have 5 columns in Datagrid .Among that 2 columns value should get from String on run time

Greetings to all
Actually i'm developing a web application Which will generate DataGrid,Button and a Label at run time depends upon the value return from database.
Eg:
if return value is 2 then the 3 controls(datagrid,button and label) will generate twice.like shown below
Application working Procedure is.On click on search button the above 3 controls are generated and bind the datagrid.I have achieved this using repeater.
Now what i need is....inside that datagrid i have a button called refresh.When the Refresh button is clicked the gross weight and volume in the datagrid should display the string value,remaining columns should not get change.
Here is my aspx code:
<asp:Repeater runat="server" OnItemDataBound="repeaterSearchResult_ItemDataBound" ID="repeaterSearchResult">
<ItemTemplate>
<asp:Label ID="textBoxSearch" ForeColor="White" width="25%" runat="server"
Text="<%#Container.DataItem%>"></asp:Label>
<asp:Button ID="BTNAdd" runat="server" Text="Add" OnClick="button_click"/>
<br />
<asp:DataGrid ID="dgLCL" runat="server" AutoGenerateColumns="False"
ShowFooter="FALSE" CellPadding="3" OnItemCommand="dgLCL_Select"
OnDeleteCommand="dgLCL_Delete">
<asp:BoundColumn DataField="GrossUOMType" HeaderText="Type">
</asp:BoundColumn>
<asp:BoundColumn DataField="Volume" HeaderText="Volume">
</asp:BoundColumn>
<asp:TemplateColumn HeaderText="DELETE">
<ItemTemplate>
<asp:ImageButton runat="server" ID="IMGBTNDelete"
ImageUrl="~/AppImages/grid-icon-delete.jpg"
ToolTip="Delete" CommandName="DeleteItem"
OnClientClick="javascript:return confirmDelete();"
AlternateText="Delete" />
</ItemTemplate>
</asp:TemplateColumn>
<asp:TemplateColumn HeaderText="Add">
<ItemTemplate>
<asp:ImageButton runat="server" ID="IMGBTNAdd"
ImageUrl="~/AppImages/grid-icon-add.jpg"
ToolTip="Insert" CommandName="InsertItem"
AlternateText="Insert" />
</ItemTemplate>
</asp:TemplateColumn>
</Columns>
<PagerStyle HorizontalAlign="Left" ForeColor="#000066" BackColor="White"
Mode="NumericPages">
</PagerStyle>
</asp:DataGrid><br />
and my code behind is:
protected void repeaterSearchResult_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
string Flag = Session["Flag"].ToString();
if (Flag=="B")
{
e.Item.FindControl("textBoxSearch").Visible = false;
e.Item.FindControl("BTNAdd").Visible = false;
}
DataGrid gv = e.Item.FindControl("dgLCL") as DataGrid;
//
Label label = e.Item.FindControl("textBoxSearch") as Label;
Session["Label"] = label.Text;
Session["FlagB"] = Flag;
Session["GV"] = gv;
gridbind(label.Text, Flag, gv);
}
void gridbind(string label,string Flag,DataGrid gv)
{
try
{
if (Session["Loading"] != null)
{
PortLName.Text = Session["Loading"].ToString();
}
if (Session["Destination"] != null)
{
PortDName.Text = Session["Destination"].ToString();
}
string SFRID = label;
if (Flag == "L")
{
sql = "Select MasterNo , MasterDate,GrossWt,GrossUOMType,Volume,tBLg_NUPKId from VW_TransLCLMaster where tBLG_mDOC_NUPKID ='107' and tBLG_NUIsActive=1 and PortOfDischargeName='" + SFRID + "'";
SqlCommand cmd = new SqlCommand(sql, con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
if (gv != null)
{
gv.DataSource = ds;
gv.DataBind();
}
}
}
catch (Exception ex)
{
}
as shown in above image i need the string values should assign to grosswt and volume on refresh button click.
Please help me thanks in advance.
In your datagrid columns add another column
<asp:TemplateColumn HeaderText="Refresh">
<ItemTemplate>
<asp:ImageButton runat="server" ID="IMGBTNRefresh"
ImageUrl="~/AppImages/grid-icon-refresh.jpg"
ToolTip="Insert" CommandName="Refresh"
AlternateText="Refresh" />
</ItemTemplate>
</asp:TemplateColumn>
In your DagaGrid's OnItemCommand event, set the text for both the cells as below
protected void dgLCL_Select(object source, DataGridCommandEventArgs e)
{
if (e.CommandName == "Refresh")
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
//Change the indexes to correct column index
e.Item.Cells[3].Text = "your dynamic gross weight text";
e.Item.Cells[5].Text = "your dynamic volumne text";
}
}
}

Categories