How to retrive textbox text from a gridview - c#

I have a gridview which contains textboxes and dropdowns.In gvScheduleBattingScore_RowDataBound Event I am binding dropdowns without any problem. The button control is outside to the gridview. I actually want to submit all the textbox values and dropdown selected values to the database on buttonclickevent But I don't know where I am going wrong.
The Problem is Textboxes do not contain any text and am getting Exception
Input string was not in a correct format.
Please help me out...
<asp:GridView ID="gvScheduleBattingScore" runat="server" AllowSorting="false" AutoGenerateColumns="False" AllowPaging="false"
GridLines="None" CellPadding="1" CssClass="GridViewStyle" ShowFooter="false" width="100%"
OnRowDataBound="gvScheduleBattingScore_RowDataBound">
<Columns>
<asp:BoundField DataField="P_PlayerId" HeaderText="Player Id" HeaderStyle-Wrap="true" HeaderStyle-Width="5%" Visible="false"/>
<asp:BoundField DataField="PlayerName" HeaderText="Player Name" HeaderStyle-Wrap="true" HeaderStyle-Width="30%"/>
<asp:TemplateField HeaderText="Playing Order" HeaderStyle-Wrap="true" HeaderStyle-Width="5%">
<ItemTemplate>
<asp:TextBox ID="txtPlayingOrder" runat="server" CssClass="TinyTexBox"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Status">
<ItemTemplate>
<asp:TextBox ID="txtStatus" runat="server"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Bold By">
<ItemTemplate>
<asp:DropDownList ID="ddlBoldBy" runat="server"> </asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</br>
<asp:Button ID="ButtonAdd" runat="server" Text="Add" CssClass="SmallButton"
ValidationGroup="Add" onclick="ButtonAdd_Click"/>
On ButtonClick Event:
protected void ButtonAdd_Click(object sender, EventArgs e)
{
SqlConnection dBConnection = null;
try
{
int playerId;
short plyerOrder;
string BatsmanStatus;
int boldBy;
dBConnection = new SqlConnection();
dBConnection.ConnectionString = ConfigurationManager.ConnectionStrings["CriConn"].ConnectionString;
SqlDataAdapter dataAdapter = new SqlDataAdapter();
SqlCommand cmd = new SqlCommand("SP_InsertScores", dBConnection);
cmd.CommandType = CommandType.StoredProcedure;
foreach (GridViewRow GVRow in gvScheduleBattingScore.Rows)
{
string textPlayerId = GVRow.Cells[0].Text;
TextBox textPlyerOrder = (TextBox)GVRow.Cells[1].FindControl("txtPlayingOrder");
TextBox textBatsmanStatus = GVRow.Cells[2].FindControl("txtStatus") as TextBox;
DropDownList DropDownBoldBy = (DropDownList)GVRow.Cells[18].FindControl("ddlBoldBy");
playerId = Convert.ToInt32(textPlayerId );
if (!string.IsNullOrEmpty(textPlyerOrder.Text))
plyerOrder = Convert.ToInt16(textPlyerOrder.Text);
if (!string.IsNullOrEmpty(textBatsmanStatus.Text))
BatsmanStatus = textBatsmanStatus.Text;
if (!string.IsNullOrEmpty(DropDownBoldBy.SelectedValue) && DropDownLbwBy.SelectedValue != "Select")
boldBy = Convert.ToInt32(DropDownBoldBy.SelectedValue);
cmd.Parameters.Add("#PlayerId", SqlDbType.NVarChar).Value = playerId;
cmd.Parameters.Add("#PlayerId", SqlDbType.Int).Value = playerId;
cmd.Parameters.Add("#plyerOrder", SqlDbType.Int).Value = plyerOrder;
cmd.Parameters.Add("#BatsmanStatus", SqlDbType.NVarChar).Value = BatsmanStatus;
dBConnection.Open();
dataAdapter.InsertCommand = cmd;
cmd.ExecuteNonQuery();
dBConnection.Close();
}
}
catch (Exception ex)
{
throw ex;
}
finally
{
// Close data reader object and database connection
cmd.Dispose();
cmd = null;
if (dBConnection.State == ConnectionState.Open)
dBConnection.Close();
}

As per the Chat discussion with #bhoopendra.sahoo, we come to the conclusion that it is a Binding issue.
When Button Click Event is fired, the GridView binds again causing the issue.
The fix is to bind the GridView only once and restrict its binding during other events.

Add a null checking before converting the textbox value to int
if (!string.IsNullOrEmpty(textPlayerId.Text))
playerId = Convert.ToInt32(textPlayerId);
Also make these changes to you code, to find the textbox controls in the correct cell
TextBox textPlyerOrder = (TextBox)GVRow.Cells[2].FindControl("txtPlayingOrder");
TextBox textBatsmanStatus = (TextBox)GVRow.Cells[3].FindControl("txtStatus");

Related

Fetch MySQL multiple row data and show in individual text box

I am trying to get the StudentFirstName from data base and show in the text box right now am using grid view where it shows the data but not in textbox am not sure how to get all the data from data base and show in individual text box.
MyDB
StudentFirstName SchoolID StudCourse
abc sc123 A
cef sc155 A
gij sc133 A
abc sc122 B
cef sc156 B
gij sc144 B
C#
using (MySqlConnection myConnection = new MySqlConnection(constr))
{
string oString = "Select StudentFirstName from student WHERE StudCourse=#DDSelected_Class order by StudentFirstName ASC";
MySqlCommand oCmd = new MySqlCommand(oString, myConnection);
oCmd.Parameters.AddWithValue("#DDSelected_Class", DDSelected_Class);
myConnection.Open();
using (MySqlDataReader oReader = oCmd.ExecuteReader())
{
if (oReader == null || !oReader.HasRows)
{
ScriptManager.RegisterStartupScript(this, typeof(Page), "alert", "alert('No Student Found')", true);
}
else
{
while (oReader.Read())
{
GridView1.DataSource = oReader;
GridView1.DataBind();
}
}
myConnection.Close();
}
}
Gridview
<asp:GridView ID="GridView1" runat="server"></asp:GridView>
You will need to define ItemTemplate for your column. It will contain a textbox and the field name name in Eval to bind it.
Complete code sample:
<asp:GridView ID="GridView1" runat="server">
<Columns>
<asp:TemplateField HeaderText="Names">
<ItemTemplate>
<asp:TextBox ID="txtName" runat="server" Text='<%# Eval("StudentFirstName ") %>' ></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<Columns>
</asp:GridView>

Exception: 'System.OutOfMemoryException' was thrown when there is 20,000+ data need to be bind in RadComboBox inside RadGrid

I have a RadGrid and a RadComboBox outside of RadGrid (say comboOutside), inside a Web Form.
Inside RadGrid, there is 1 more RadComboBox (say comboRadGrid). On selection of items from comboOutside, comboRadGrid is bind i.e., If item 'Company' is selected from comboOutside, then all the company names will be bind in comboRadGrid; and then user select specific company from comboRadGrid and records are added in RadGrid.
For all items, functionality is working fine but I am facing issue in binding of a specific comboOutside item.
i.e., When I choose a specific item from comboOutside, say I have 100 items inside comboOutside, and when I select 35th items from it, then comboRadGrid always throw this error while binding records for 35th item (since 35th item has 2000+ records to bind in comboRadGrid)
Error is below:
Funcitonality is working fine for all the items except 1 specific item of RadComboBox. I don't understand why. Due to this I am unable to add records in RadGrid
Below is my code-
C# code
public DataTable GetAccCode(string CompanyCode)
{
SqlConnection con = new SqlConnection(strcon);
SqlCommand cmd = new SqlCommand("[Invoice].[usp_tbl_AccountCode_DL_Test]", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#CompanyCode", CompanyCode);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
try
{
con.Open();
da.Fill(dt);
con.Close();
}
catch (Exception ex)
{
}
return dt;
}
protected void RGGSTAcCode_ItemDataBound(object sender, GridItemEventArgs e)
{
if (e.Item is GridEditableItem && e.Item.IsInEditMode)
{
//bind dropdwon while "Add"
string CompanyCode = ddlCompany.SelectedValue.ToString();
GridEditableItem item = (GridEditableItem)e.Item;
//code to bind inside RadComboBox list
RadComboBox rcb = (RadComboBox)item.FindControl("ddlAccountCode");
rcb.DataSource = GetAccCode(CompanyCode);
rcb.DataTextField = "AccountDescription";
rcb.DataValueField = "AccountCodeID";
rcb.DataBind();
rcb.Items.Insert(0, new RadComboBoxItem("- Select -", string.Empty));
Session["AccCode"] = rcb.SelectedValue.ToString();
string a = rcb.SelectedValue.ToString();
//Select particular dropdown value while "Edit"
Label lblAcCode2 = item.FindControl("lblAcCode2") as Label;
if (!string.IsNullOrEmpty(lblAcCode2.Text))
{
rcb.SelectedValue = lblAcCode2.Text;
rcb.SelectedItem.Text = lblAcCode2.Text;
}
}
}
//code to bind outside RadComboBox list
protected void BindComapnyDL()
{
SqlConnection con = new SqlConnection(strcon);
SqlCommand cmd = new SqlCommand("General.usp_tbl_BuyerCode_Query", con);
cmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
try
{
con.Open();
da.Fill(dt);
con.Close();
}
catch (Exception ex)
{
}
ddlCompany.DataTextField = "Title";
ddlCompany.DataValueField = "Code";
ddlCompany.DataSource = dt;
ddlCompany.DataBind();
Session["Comp"] = ddlCompany.SelectedValue.ToString();
string a = ddlCompany.SelectedValue.ToString();
}
//RadComboBox select index changed event
protected void ddlCompany_SelectedIndexChanged(object sender, RadComboBoxSelectedIndexChangedEventArgs e)
{
if (ddlCompany.SelectedValue == null || ddlCompany.SelectedValue == "")
{
GridCommandItem cmditem = (GridCommandItem)RGGSTAcCode.MasterTableView.GetItems(GridItemType.CommandItem)[0];
System.Web.UI.WebControls.Button ctrl = (System.Web.UI.WebControls.Button)cmditem.FindControl("AddNewRecordButton");
ctrl.Enabled = false;
System.Web.UI.WebControls.LinkButton btn = (System.Web.UI.WebControls.LinkButton)cmditem.FindControl("InitInsertButton");
btn.Enabled = false;
string content = "Please select company first";
ScriptManager.RegisterStartupScript(this, typeof(string), "Successful", "alert('" + content + "');", true);
}
else
{
RGGSTAcCode.Rebind();
}
}
HTML code
<telerik:RadComboBox ID="ddlCompany" runat="server" Height="200" Width="240"
DropDownWidth="310" EmptyMessage="- Select Product -" HighlightTemplatedItems="true" CausesValidation="false"
Filter="Contains" AppendDataBoundItems="true" AllowCustomText="true" AutoPostBack="true"
DataTextField="Title" DataValueField="Code" OnSelectedIndexChanged="ddlCompany_SelectedIndexChanged">
</telerik:RadComboBox>
<telerik:RadGrid ID="RGGSTAcCode" runat="server"
ShowFooter="True" GroupingEnabled="False" ShowStatusBar="true" EmptyDataText="No record available."
AllowAutomaticInserts="False" AllowAutomaticUpdates="False" AllowAutomaticDeletes="true"
OnNeedDataSource="RGGSTAcCode_NeedDataSource" OnItemDataBound="RGGSTAcCode_ItemDataBound"
OnInsertCommand="RGGSTAcCode_InsertCommand" OnDeleteCommand="RGGSTAcCode_DeleteCommand"
OnUpdateCommand="RGGSTAcCode_UpdateCommand" OnItemCommand="RGGSTAcCode_ItemCommand">
<mastertableview ShowHeadersWhenNoRecords="true" autogeneratecolumns="false" datakeynames="AccountCodeID" InsertItemDisplay="Top"
insertitempageindexaction="ShowItemOnCurrentPage" ShowFooter="True" CommandItemDisplay="Top" ClientIDMode="Static">
<Columns>
<telerik:GridEditCommandColumn ButtonType="ImageButton" UniqueName="EditCommandColumn"></telerik:GridEditCommandColumn>
<telerik:GridTemplateColumn UniqueName="AccountCode" HeaderText="Account Code">
<ItemTemplate>
<asp:Label ID="lblAcCode" runat="server" Text='<%# Eval("AccountCode")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:Label ID="lblAcCode2" runat="server" Text='<%# Eval("AccountCode") + " - " + Eval("AccountDescription")%>' Visible="false"></asp:Label>
<telerik:RadComboBox ID="ddlAccountCode" runat="server" Height="200" Width="240"
DropDownWidth="310" HighlightTemplatedItems="true" CausesValidation="true"
Filter="Contains" AppendDataBoundItems="true" DataTextField="AccountDescription" DataValueField="AccountCodeID">
</telerik:RadComboBox>
</EditItemTemplate>
</telerik:GridTemplateColumn>
<telerik:GridBoundColumn DataField="AccountDescription" HeaderText="Description" UniqueName="AccountDescription" SortExpression="AccountDescription" InsertVisiblityMode="AlwaysHidden" ReadOnly="true" ></telerik:GridBoundColumn>
<telerik:GridBoundColumn aggregate="SUM" DataField="Amount" HeaderText="Amount" FooterAggregateFormatString="Total : {0:###,##0.00}" DataFormatString="{0:n}" FooterStyle-BackColor="#ffc04c" UniqueName="Amount" SortExpression="Amount"></telerik:GridBoundColumn>
<telerik:GridBoundColumn DataField="Remark" HeaderText="IFCA Remark" UniqueName="Remark" SortExpression="Remark">
</telerik:GridBoundColumn>
<telerik:GridButtonColumn ConfirmTextFormatString="Are you sure you want to Delete {0} Account Code?" ConfirmTextFields="AccountCodeID"
ConfirmDialogType="RadWindow" CommandName="Delete" Text="Delete" UniqueName="DeleteColumn"></telerik:GridButtonColumn>
</Columns>
<EditFormSettings>
<EditColumn ButtonType="ImageButton" />
</EditFormSettings>
<CommandItemSettings AddNewRecordText="Add new record" RefreshText="Refresh"></CommandItemSettings>
</mastertableview>
</telerik:RadGrid>
Please let me know why this error is coming for a specific item of RadComboBox selection.
Used LoadOnDemand mechanish, by following this link: demos.telerik.com/aspnet-ajax/combobox/examples/…
This approach is used for large number of records to be bind in RadComboBox which will avoid such exceptions to occur. And its working fine. Thank you #Icemanind for the help.

How to call a function at regular interval which accesses and updates UI controls?

The basic Idea of this web app is a chatroom and the GridView showing the chats should be refreshed by selecting latest chats from database and storing in DataTable which is the DataSource of the Gridview. The GridView's markup is as follows:-
<asp:GridView ID="GridView2" runat="server" AutoGenerateColumns="False"
Width="545px" HeaderStyle-BorderStyle="None" HeaderStyle-Height="0px">
<Columns>
<asp:TemplateField>
<HeaderStyle Height="0px" Wrap="False" />
<ItemStyle BackColor="#CCCCCC" ForeColor="Black" Width="394px"
BorderStyle="None" />
<ItemTemplate>
<asp:Label ID="Label3" runat="server" Text='<%# Bind("user") %>'></asp:Label>
<asp:Label ID="Label4" runat="server" Text=": "></asp:Label>
<asp:Label ID="Label1" runat="server" Text='<%# Bind("chat") %>'></asp:Label><br />
<asp:Label ID="Label2" runat="server" Text='<%# Bind("date") %>' Font-Size="Small" ForeColor="Gray"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<HeaderStyle BorderStyle="None" Height="0px" />
</asp:GridView>
There's of course another GridView containing users names. When one of them is clicked the RowCommand event is fired:-
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
int rowValue = Convert.ToInt32(e.CommandArgument.ToString());
GridView1.SelectedIndex = rowValue;
show_chats();
}
And Finally, here's the show_chats function:-
public void show_chats()
{
if (GridView1.SelectedIndex >= 0)
{
LinkButton ul = (LinkButton)GridView1.Rows[GridView1.SelectedIndex].FindControl("userList");
string gridViewValue = ul.Text;
conn.Open();
SqlDataAdapter sda = new SqlDataAdapter("select * from chats where (chatFrom='" + user + "' and chatTo='" + gridViewValue + "') OR (chatFrom='" + gridViewValue + "' and chatTo='" + user + "') order by dateTime", conn);
conn.Close();
DataTable dt = new DataTable();
sda.Fill(dt);
if (dt.Rows.Count == 0)
{
txtChat.Text = "No past chats, Type here to get started";
chats.Clear();
GridView2.DataSource = chats;
GridView2.DataBind();
}
else
{
chats.Clear();
for (int i = 0; i < dt.Rows.Count; i++)
{
DataRow row = chats.NewRow();
row[0] = dt.Rows[i][0].ToString();
row[1] = dt.Rows[i][2].ToString();
row[2] = dt.Rows[i][3].ToString();
chats.Rows.Add(row);
}
GridView2.DataSource = chats;
GridView2.DataBind();
txtChat.Text = "";
}
}
}
Now I want the show_chats function to be called at regular interval to check for new messages whenever an user is selected from GridView1 (which contains the user names).
I tried using thread but I guess I'm doing it wrong, because it is throwing exceptions which are not thrown when I am not using thread.
If I have to use threading please tell me how to use it properly.
Use 'Threading.Thread' for independent execution of a function and Threading.Timer to call that function on interval.
Declaring Threading.Timer :
System.Threading.Timer TimerForXYZ = new System.Threading.Timer(TickForXYZ, null, 0, 1000); // this will call method TickForXYZ after every 1 second
Declaring Threading.Thread :
private void TickForXYZ(object obj)
{
Thread myThreadXYZ = new Thread(new System.Threading.ThreadStart(XYZ));
myThreadXYZ .IsBackground = true;
myThreadXYZ .Start();
}
Your Method to run periodically :
private void XYZ()
{
// Your code goes here
// This function will run after every 1s
}
Alternately you can use timers in javascript to call a ajax function, which will load your grid.
Let me know if you need any help with this.

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";
}
}
}

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

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" />

Categories