Delete row from asp gridview via a LinkButton - c#

I have been spending quite long time on research how to do this but had no luck.
<asp:GridView runat="server" ID="TBDSPCGrid"
AutoGenerateColumns="false"
AllowPaging="true"
AllowSorting="false"
DataKeyNames="SPID,CategoryId,Category,RowNum, PurchaseDate, Title, Description,SFItemId"
OnRowDataBound="TBDSPC_RowDataBound"
OnRowCreated="TBDSPC_RowCreated"
OnRowCommand="TBDSPC_Command"
OnPageIndexChanging="TBDSPC_PageIndexChanging"
OnRowDeleting="TBDSPC_OnRowDeleting">
<Columns>
<asp:TemplateField HeaderText="Timeouts" ItemStyle-Width="40px" ItemStyle-Wrap="false"
ItemStyle-CssClass="padding-right">
<ItemTemplate>
<div class="targeted-icons">
<asp:LinkButton runat="server" id="LinkButton1" CommandName="delete" CommandArgument='<%#Eval("SFItemId")%>'
><img src="delete.png" /></asp:LinkButton>
</div>
</ItemTemplate>
</asp:TemplateField>
So what should I do here?
protected void TBDSPCGrid_OnRowDeleting(object sender, GridViewDeleteEventArgs e)
{
// do something
}
I tried this but it is not working...it gave me an error of "object reference not set to an instance of an object"
protected void TBDSPC_Command(object sender, GridViewCommandEventArgs e)
{
GridView gv = (GridView)sender;
switch (e.CommandName)
{
case "delete":
{
DataTable test = TargetedSpView.ToTable();
test.Rows[0].Delete();
test.AcceptChanges();
TargetedSpView = test.DefaultView;
this.TBDSPCGrid.DataSource = this.TargetedSpView;
this.TBDSPCGrid.DataBind();
}
break;
}
}

protected void TBDSPC_Command(object sender, GridViewCommandEventArgs e)
{
GridView gv = (GridView)sender;
switch (e.CommandName)
{
case "delete":
{
DataTable test = RetrieveData(0, 0); // this is a function I used to get a datatable
test.Rows[0].Delete();
test.AcceptChanges();
TargetedSpView = test.DefaultView;
TBDSPCGrid.DataSource = TargetedSpView;
TBDSPCGrid.DataBind();
}
break;
}
}

Related

ASP.net prevent gridview row click in edit mode

I have some issue with ASP.net Gridview that I hope people here can help me.
Requirements
Gridview whole row to be clickable to open another page
In editing mode, can change table values through edititemtemplate textbox
Problem
Textbox selection causes the entire row click event to fire and prevents user from changing the textbox text. User can edit table value without opening different page.
ASP Page
<asp:GridView ID="remarksGV1" runat="server" AllowPaging="true" DataKeyNames="REM_ID"
OnRowDataBound="remarksGV1_RowDataBound" OnSelectedIndexChanged="remarksGV1_SelectedIndexChanged"
OnRowEditing="remarksGV1_RowEditing"
OnRowCancelingEdit="remarksGV1_RowCancelingEdit"
OnRowUpdating="remarksGV1_RowUpdating"
AutoPostBack="false"
HeaderStyle-CssClass="thead-dark"
CssClass="table table-striped thead-dark table-borderless table-hover border-0 hand"
AutoGenerateColumns="false">
<Columns>
<asp:TemplateField HeaderText="No.">
<ItemTemplate>
<%# Container.DataItemIndex + 1 %>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Title">
<ItemTemplate>
<asp:Label ID="titleLbl" runat="server" Text='<%# Bind("REM_TITLE") %>' />
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="titleTB" runat="server" />
</EditItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="REM_DESC" HeaderText="Remarks Description" ReadOnly="true" />
<asp:BoundField DataField="CREATE_DATE" DataFormatString="{0:d}" HeaderText="Date Created" ReadOnly="true" />
<asp:BoundField DataField="UPD_DATE" DataFormatString="{0:d}" HeaderText="Last Updated" ReadOnly="true" />
<asp:TemplateField>
<ItemTemplate>
<asp:Button Text="Edit" ID="EditBtn" CssClass="btn-action" runat="server" CommandName="Edit" />
</ItemTemplate>
<EditItemTemplate>
<asp:Button Text="Update" ID="UpdateBtn" CssClass="btn-action" runat="server" CommandName="Update" />
<asp:Button Text="Cancel" ID="CancelBtn" CssClass="btn-action" runat="server" CommandName="Cancel" />
</EditItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Code behind
private void BindGrid()
{
Debug.WriteLine("BindGrid called");
int proj_code = Int32.Parse(ViewState["proj_cd"].ToString());
ProjectRepository remarksRepository = new ProjectRepository();
var remarks = remarksRepository.GetRemarks(proj_code, proj_task_code, proj_stask1_cd, proj_stask2_cd);
remarksGV1.DataSource = remarks;
remarksGV1.DataBind();
}
protected void Unnamed_Click(object sender, EventArgs e)
{
Launch.PageEvent(this, (LinkButton)sender, ViewState["proj_cd"].ToString());
}
protected void remarksGV1_RowDataBound(object sender, GridViewRowEventArgs e)
{
try
{
switch (e.Row.RowType)
{
case DataControlRowType.Header:
//...
break;
case DataControlRowType.DataRow:
e.Row.Attributes.Add("onclick", Page.ClientScript.GetPostBackEventReference(remarksGV1, "Select$" + e.Row.RowIndex.ToString()));
break;
}
}
catch
{
//...throw
}
if (e.Row.RowType == DataControlRowType.DataRow)
{
TextBox titleTB = (e.Row.FindControl("titleTB") as TextBox);
int prj_cd = Int32.Parse(ViewState["proj_cd"].ToString());
ProjectRepository repository = new ProjectRepository();
var remarks = repository.GetRemarks(prj_cd, proj_task_code, proj_stask1_cd, proj_stask2_cd);
Debug.WriteLine("Remarks Count: " + remarks.Count);
TMS_PROJ_REMARK remark = remarks.First(x => x.REM_ID == Convert.ToInt64(DataBinder.Eval(e.Row.DataItem, "REM_ID")));
if (titleTB != null)
{
titleTB.Text = remark.REM_TITLE;
}
}
}
protected void remarksGV1_SelectedIndexChanged(object sender, EventArgs e)
{
int row = remarksGV1.SelectedIndex;
long rem_id = (long)remarksGV1.DataKeys[row]["REM_ID"];
Debug.WriteLine("REM ID: " + rem_id);
Session["edit_remarks"] = true;
Dictionary<string, string> pairs = new Dictionary<string, string>();
pairs["rem_id"] = rem_id.ToString();
pairs["proj_cd"] = ViewState["proj_cd"].ToString();
Launch.ToPage(this, "Project_Remarks_In_2.aspx", pairs);
}
protected void btnAddRemarks_Click(object sender, EventArgs e)
{
Session["new_remarks"] = true;
Dictionary<string, string> pairs = new Dictionary<string, string>();
pairs["proj_cd"] = ViewState["proj_cd"].ToString();
string url = "Project_Remarks_In_1.aspx";
Launch.ToPage(this, url, pairs);
}
private void SetTitle()
{
ProjectRepository repository = new ProjectRepository();
TMS_PROJ_MASTER project = repository.GetProject(Convert.ToInt32(ViewState["proj_cd"]));
this.Title = "Remarks - " + project.PROJ_TITLE;
}
protected void remarksGV1_RowEditing(object sender, GridViewEditEventArgs e)
{
remarksGV1.EditIndex = e.NewEditIndex;
BindGrid();
}
protected void remarksGV1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
// Do stuff
ProjectRepository repository = new ProjectRepository();
GridViewRow row = remarksGV1.Rows[e.RowIndex];
TextBox titleTB = (row.FindControl("titleTB") as TextBox);
long rem_id = Convert.ToInt64(remarksGV1.DataKeys[e.RowIndex].Value);
var db = new THPEntities();
TMS_PROJ_REMARK remark = db.TMS_PROJ_REMARK
.First(x => x.REM_ID == rem_id);
remark.REM_TITLE = titleTB.Text;
remark.UPD_DATE = DateTime.Now;
db.SaveChanges();
// Bind Grid
remarksGV1.EditIndex = -1;
BindGrid();
}
protected void remarksGV1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
remarksGV1.EditIndex = -1;
BindGrid();
}
I suggest in this part of your code, do not add the full line click when you edit the line (I have add one -if- to check for the edit).
switch (e.Row.RowType)
{
case DataControlRowType.Header:
//...
break;
case DataControlRowType.DataRow:
if((e.Row.RowState & DataControlRowState.Edit) != DataControlRowState.Edit)
e.Row.Attributes.Add("onclick", Page.ClientScript.GetPostBackEventReference(remarksGV1, "Select$" + e.Row.RowIndex.ToString()));
break;
}

Call Code Behind method (function) in RowCreated Gridview's handler

I want to call a Code Behind method inside a Gridview.
This is the Code Behind method that loops through every webcontrol that’s in the form:
private void SetupJSdataChange(Control parentControl)
{
foreach (Control control in parentControl.Controls)
{
//Response.Write(control.ID + "<br>");
if (control is WebControl)
{
WebControl webControl = control as WebControl;
webControl.Attributes.Add("onchange", "InputChanged(this)");
}
}
}
And I want it to loop through every webcontrol that’s in a RowCreated gridview's handler instead. This is my try:
protected void GVTrabajadores_RowCreated(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
foreach (Control control in parentControl.Controls)
{
//Response.Write(control.ID + "<br>");
if (control is WebControl)
{
WebControl webControl = control as WebControl;
webControl.Attributes.Add("onchange", "InputChanged(this)");
}
}
}
}
But I get an error that says "the name 'parentControl' doesn't exist in the current context" and I don't know how to handle it.
And this is the Gridview:
<asp:GridView ID="GVTrabajadores" runat="server"
CssClass="table table-hover table-striped"
ShowHeaderWhenEmpty = "true"
GridLines="None"
AutoGenerateColumns="False"
ShowFooter="true"
OnRowCreated="GVTrabajadores_RowCreated"
OnRowCommand="GVTrabajadores_RowCommand">
<Columns>
<asp:TemplateField HeaderText="Nombre">
<ItemTemplate>
<asp:TextBox ID="TxNombre" runat="server" Text='<%#Eval("nombre") %>' />
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="TxNombref" runat="server" />
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Cerrada">
<ItemTemplate>
<asp:CheckBox ID="CBCerrada" runat="server" Checked='<%# (Eval("cerrada").ToString() == "1" ? true : false) %>' />
</ItemTemplate>
<FooterTemplate>
<asp:CheckBox ID="CBCerradaf" runat="server" />
</FooterTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
This should work for you. Note that I used generic event args - if you need them you'll need to change them.
private void GVTrabajadores_RowCreated(object sender, GridViewRowEventArgs e)
{
GridView gV = sender as GridView;
for(int i = 0; i < gV.Columns.Count; i++)
{
Control c = e.Row.Cells[i].Controls[0];
string controlType = c.GetType().ToString().Replace("System.Web.UI.WebControls.", "");
switch (controlType)
{
case "TextBox":
TextBox t = c as TextBox;
t.TextChanged += GVTrabajadores_TextBox_TextChanged;
t.AutoPostBack = true;
break;
case "CheckBox":
CheckBox cB = c as CheckBox;
cB.CheckedChanged += GVTrabajadores_CheckBox_Changed;
cB.AutoPostBack = true;
break;
}
}
}
private void GVTrabajadores_CheckBox_Changed(object sender, EventArgs e)
{
//process change
}
private void GVTrabajadores_TextBox_TextChanged(object sender, EventArgs e)
{
//process changed text
}

How to change ButtonField text in asp.net

<asp:TemplateField HeaderText="ID" SortExpression="CareerFormID">
<ItemTemplate>
<asp:Label ID="CareerFormID" runat="server" Text='<%#Eval("CareerFormID")%>' />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField HeaderText="Checked" DataField="checked" />
<asp:ButtonField Text="Edit" CommandName="Select" ButtonType="Link" />
protected void OnSelectedIndexChanged(object sender, EventArgs e)
{
string idtemp = (GridView1.SelectedRow.FindControl("CareerFormID") as Label).Text;
Session["CompanyFormID"] = idtemp;
Response.Redirect("Management_Edit.aspx");
//Response.Write(Session["CompanyFormID"]);
}
I want to change ButtonField text="Modify" when DataField="checked" is 1, How can I do this?
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
if (e.Row.Cells[4].Text == "1")
{
e.Row.Cells[4].Text = "Yes";
e.Row.Cells[4].ForeColor = System.Drawing.Color.Green;
e.Row.Cells[6].Text = "Modify";
}
else if (e.Row.Cells[4].Text == "0")
{
e.Row.Cells[4].Text = "No";
e.Row.Cells[4].ForeColor = System.Drawing.Color.Red;
}
}
}
But this don't work, the cells[6] text is changed but the link is cancel.
For Example like that, the link can not working when I change the text
http://i.imgur.com/CN5snv6.jpg
Makes event handler when DataField="checked" is 1 (I don't find it in your code, how to make it to 1) and do this
//begin of event handler
//check datafield="checked" is 1, I still don't get it this one
ButtonField.Text="Modify"
//end of event handler

Telerik radgrid paging in webshop, breaks when changing product amount on last page

I'm having some problems with one of our webshops.
A Telerik radgrid works as the cart and lists all products currently in the cart.
The paging on the Radgrid correctly splits the cart view into different pages.
The problem occurs when one manually tries to change the amount of a product, but only if the product is on the LAST page of the radgrid and only if the number of products are less than the page size limit.
I can't post images yet, so have to give you a link.
Image link http://i.stack.imgur.com/hfFIx.jpg
I have figured it out as much as the radgrid believes there are always an even amount of products, based on the radgrid's page size.
The crash occurs in the tbQuantity_TextChanged event handler, more specific when var shopItemID = Convert.ToInt32(item.GetDataKeyValue("ID")); is called for an item that doesn't exist on this page, but on another page.
The exception is
System.ArgumentOutOfRangeException was unhandled by user code
Message=Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index
Gridview code
<%# Control Language="C#" AutoEventWireup="true" CodeBehind="ShopItems.ascx.cs" Inherits="Litho.Framework.Web.Modules.Shop.ShopItems" %>
<%# Register Assembly="Telerik.Web.UI" Namespace="Telerik.Web.UI" TagPrefix="telerik" %>
<telerik:RadGrid
ID="gvCartItems"
runat="server"
AutoGenerateColumns="False"
AllowPaging="True"
PageSize="5"
Skin="Default"
GridLines="None"
AllowFilteringByColumn="False"
AllowSorting="True"
ShowFooter="True"
OnNeedDataSource="gvCartItems_NeedDataSource"
OnItemCreated="gvCartItems_ItemCreated"
OnItemDataBound="gvCartItems_ItemDataBound"
OnDeleteCommand="gvCartItems_DeleteCommand">
<MasterTableView Width="100%" NoMasterRecordsText="Inga artiklar" ShowHeadersWhenNoRecords="false" DataKeyNames="ID">
<Columns>
<telerik:GridButtonColumn ButtonType="ImageButton" CommandName="Delete" Text="Radera" UniqueName="DeleteColumn" HeaderStyle-Width="20" />
<telerik:GridTemplateColumn HeaderText="Antal" HeaderStyle-Width="110px" DataField="Quantity" UniqueName="Quantity" Aggregate="Sum" FooterText="Totalt antal: ">
<ItemTemplate>
<telerik:RadNumericTextBox
ID="tbQuantity"
runat="server"
AutoPostBack="true"
Width="70px"
MinValue="1"
Visible="false"
ShowSpinButtons="true"
IncrementSettings-InterceptArrowKeys="false"
NumberFormat-GroupSizes="9"
NumberFormat-DecimalDigits="0"
IncrementSettings-InterceptMouseWheel="true"
NumberFormat-AllowRounding="False"
OnTextChanged="tbQuantity_TextChanged">
<EnabledStyle HorizontalAlign="Right" />
</telerik:RadNumericTextBox>
<telerik:RadComboBox ID="ddlQuantity" DataTextField="Quantity" DataValueField="Quantity" Visible="false" runat="server" Width="50px" AutoPostBack="true" OnSelectedIndexChanged="ddlQuantity_SelectedIndexChanged" />
</ItemTemplate>
</telerik:GridTemplateColumn>
<telerik:GridBoundColumn HeaderText="Artnr" ReadOnly="True" DataField="ArticleNumber" UniqueName="ArticleNumber" HeaderStyle-Width="80" />
<telerik:GridTemplateColumn HeaderText="Artikel" UniqueName="Title" ShowFilterIcon="false">
<ItemTemplate>
<asp:HyperLink ID="hlTitle" runat="server" />
</ItemTemplate>
</telerik:GridTemplateColumn>
<telerik:GridTemplateColumn HeaderText="a`pris" UniqueName="Price" ShowFilterIcon="false">
<ItemTemplate>
<asp:Label ID="lblUnitprice" runat="server" />
</ItemTemplate>
</telerik:GridTemplateColumn>
<telerik:GridTemplateColumn HeaderText="Totalpris" UniqueName="Totalprice" ShowFilterIcon="false">
<ItemTemplate>
<asp:Label ID="lblTotalPrice" runat="server" />
</ItemTemplate>
</telerik:GridTemplateColumn>
</Columns>
</MasterTableView>
<FooterStyle Font-Bold="true" BackColor="#e6e6e6" />
<PagerStyle Mode="NextPrevAndNumeric" />
<FilterMenu EnableTheming="True">
<CollapseAnimation Duration="200" Type="OutQuint" />
</FilterMenu>
</telerik:RadGrid>
<asp:PlaceHolder ID="phItemSummary" runat="server" />
Code behind
using System;
using System.Collections.Generic;
using System.Web.UI;
using System.Web.UI.WebControls;
using Litho.Framework.BusinessLayer;
using Litho.Framework.BusinessLayer.Base;
using Litho.Framework.BusinessLayer.Base.Settings;
using Litho.Framework.BusinessLayer.Modules.Shop;
using Litho.Framework.PresentationLayer;
using Litho.Framework.ServiceLayer;
using Telerik.Web.UI;
namespace Litho.Framework.Web.Modules.Shop
{
public partial class ShopItems : UserControl
{
IShopItemHolder _shopItemHolder = null;
bool _readMode = true;
SessionHelper _sessionHelper = new SessionHelper();
#region Public methods
public void LoadItems(IShopItemHolder shopItemHolder, bool readMode)
{
_shopItemHolder = shopItemHolder;
_readMode = readMode;
gvCartItems.Rebind();
loadItemsSummary();
}
private void loadItemsSummary()
{
phItemSummary.Controls.Clear();
var ucItemSummary = (ShopItemsSummary)Page.LoadControl("~/Modules/Shop/ShopItemsSummary.ascx");
ucItemSummary.LoadItemSummary(_shopItemHolder);
phItemSummary.Controls.Add(ucItemSummary);
}
#endregion
#region Events
protected void gvCartItems_NeedDataSource(object source, GridNeedDataSourceEventArgs e)
{
gvCartItems.DataSource = _shopItemHolder.Items;
}
protected void gvCartItems_ItemCreated(object sender, GridItemEventArgs e)
{
if (e.Item is GridDataItem)
{
var item = (GridDataItem)e.Item;
var btnDelete = (ImageButton)item["DeleteColumn"].Controls[0];
btnDelete.ImageUrl = string.Format("~/Base/Themes/{0}/Images/Icons16x16/iconDelete.png", SettingsManager.GetGlobalSettings().AdminTheme);
btnDelete.Visible = !_readMode;
}
}
protected void gvCartItems_ItemDataBound(object sender, GridItemEventArgs e)
{
if (e.Item is GridDataItem)
{
var shopItem = (IShopItem)e.Item.DataItem;
var hlTitle = (HyperLink)e.Item.FindControl("hlTitle");
var lblUnitPrice = (Label)e.Item.FindControl("lblUnitprice");
var lblTotalPrice = (Label)e.Item.FindControl("lblTotalPrice");
if (!shopItem.IsExternal)
{
var tbQuantity = (RadNumericTextBox)e.Item.FindControl("tbQuantity");
tbQuantity.ShowSpinButtons = !_readMode;
tbQuantity.Text = shopItem.Quantity.ToString();
tbQuantity.Visible = true;
tbQuantity.Enabled = !_readMode;
}
else
{
if (!_readMode)
{
var ddlQuantity = (RadComboBox)e.Item.FindControl("ddlQuantity");
ddlQuantity.DataSource = shopItem.PriceCollection;
ddlQuantity.DataBind();
ddlQuantity.SelectedValue = shopItem.Quantity.ToString();
ddlQuantity.Visible = true;
}
}
if (!shopItem.IsExternal)
{
var parameters = new Dictionary<string, string>();
parameters.Add(KeyMaster.RequestParamsNames.Modules.Shop.PRODUCT_ID, shopItem.ID.ToString());
hlTitle.NavigateUrl = new FWContent().GetContentUrl(ModuleIDConstant.SHOP, ContentIDConstant.Shop.PRODUCT_VIEW, parameters);
}
hlTitle.Text = shopItem.Title;
lblUnitPrice.Text = shopItem.Price.ToString("0.00") + " SEK";
lblTotalPrice.Text = shopItem.GetCost(false).ToString("0.00") + " SEK";
}
}
protected void tbQuantity_TextChanged(object sender, EventArgs e)
{
if (!_readMode)
{
RadNumericTextBox tbQuantity;
foreach (GridDataItem item in gvCartItems.Items)
{
if (item is GridDataItem)
{
tbQuantity = item.FindControl("tbQuantity") as RadNumericTextBox;
var shopItemID = Convert.ToInt32(item.GetDataKeyValue("ID"));
var shopItem = _sessionHelper.CurrentCart.CartItems.Find(x => x.ID == shopItemID);
if (!shopItem.IsExternal)
{
_sessionHelper.CurrentCart.CartItems.Find(x => x.ID == shopItemID).Quantity = Convert.ToInt32(tbQuantity.Text);
_sessionHelper.CurrentCart.CartItems.Find(x => x.ID == shopItemID).TotalPrice = _sessionHelper.CurrentCart.GetItemCost(shopItemID, false);
_shopItemHolder = _sessionHelper.CurrentCart;
}
}
}
loadItemsSummary();
gvCartItems.Rebind();
}
}
protected void gvCartItems_DeleteCommand(object source, GridCommandEventArgs e)
{
if (!_readMode)
{
var cartItemID = (int)e.Item.OwnerTableView.DataKeyValues[e.Item.ItemIndex]["ID"];
_sessionHelper.CurrentCart.DeleteItem(cartItemID);
_shopItemHolder = _sessionHelper.CurrentCart;
if (_sessionHelper.CurrentCart.Items.Count == 0)
{
Response.Redirect(new FWContent().GetContentUrl(ModuleIDConstant.SHOP, ContentIDConstant.Shop.CART));
}
else
{
gvCartItems.Rebind();
loadItemsSummary();
}
}
}
protected void ddlQuantity_SelectedIndexChanged(object sender, EventArgs e)
{
RadComboBox ddlQuantity;
foreach (GridDataItem item in gvCartItems.Items)
{
if (item is GridDataItem)
{
ddlQuantity = item.FindControl("ddlQuantity") as RadComboBox;
var cartItemID = Convert.ToInt32(item.GetDataKeyValue("ID"));
var cartItem = _sessionHelper.CurrentCart.CartItems.Find(x => x.ID == cartItemID);
if (cartItem.IsExternal)
{
cartItem.Quantity = Convert.ToInt32(ddlQuantity.Text);
cartItem.TotalPrice = getProductPrice(cartItem);
}
}
}
loadItemsSummary();
gvCartItems.Rebind();
}
#endregion
private double getProductPrice(CartItem cartitem)
{
foreach (var price in cartitem.PriceCollection)
{
if (price.Quantity == cartitem.Quantity)
{
return price.Price;
}
}
throw new Exception(); // todo lägg till customexception
}
}
}
Thanks in advance!
Edit:
Small update, I've been trying to work something out with CustomPaging, but no luck so I am still using the posted code as it is.
I find it strange that the paging works as it should now, it is just when I change amount on the last page that it crashes.
The guys at Telerik helped me, the problem was that I was going through all items and not just the one where the amount changed.
Updated tbQuantity_TextChanged
protected void tbQuantity_TextChanged(object sender, EventArgs e)
{
if (!_readMode)
{
RadNumericTextBox tbQuantity = (RadNumericTextBox)sender;
GridDataItem dataItem = (GridDataItem)tbQuantity.NamingContainer;
var shopItemID = (int)dataItem.GetDataKeyValue("ID");
var shopItem = _sessionHelper.CurrentCart.CartItems.Find(x => x.ID == shopItemID);
if (!shopItem.IsExternal)
{
_sessionHelper.CurrentCart.CartItems.Find(x => x.ID == shopItemID).Quantity = Convert.ToInt32(tbQuantity.Text);
_sessionHelper.CurrentCart.CartItems.Find(x => x.ID == shopItemID).TotalPrice = _sessionHelper.CurrentCart.GetItemCost(shopItemID, false);
_shopItemHolder = _sessionHelper.CurrentCart;
}
loadItemsSummary();
gvCartItems.Rebind();
}
}

Write GridView to .csv file c# asp.net

I am working on developing a website where customers order directly from our website. I had code working until a few days ago when I changed how the GridView was edited. I had previously set the GridView to AutoGenerate Columns, and have changed that since I needed more functionality for the edit feature. Here is how I create the table (created when user clicks a button to add a quick detail with the GridView):
public void CreateTable()
{
try
{
DataTable table = new DataTable();
if (Session["table"] != null)
table = (DataTable)Session["table"];
else
{
table.Columns.Add("Part Number", typeof(string));
table.Columns.Add("Quantity", typeof(Int32));
table.Columns.Add("Ship-To", typeof(string));
table.Columns.Add("Requested Date", typeof(string));
table.Columns.Add("Shipping Method", typeof(string));
}
DataRow row = table.NewRow();
row["Part Number"] = part;
row["Quantity"] = qty;
row["Ship-To"] = shipto;
row["Requested Date"] = reqdate;
row["Shipping Method"] = shipmthd;
table.Rows.Add(row);
Session["table"] = table;
griditems.DataSource = table.DefaultView;
griditems.DataBind();
}
catch
{
//error message
}
}
This displays the Gridview and allows users to edit/delete the items as they choose. Then I have another button that is displayed when the GridView is created that actually writes the .csv file to the server (my computer for the moment until deployment). Here is the code for that:
protected void orderbtn_Click(object sender, EventArgs e)
{
try
{
//ordernum++;
//custordernum = ordernum.ToString("0000000");
if (userlbl.Visible == false && userlbl2.Visible == false)
{
GlobalList.OnlineOrderNum.Add(custordernum, ordernum);
FileStream fs = new FileStream(#"C:\Web_Order\Orders.Bin", FileMode.Create);
BinaryFormatter bf = new BinaryFormatter();
bf.Serialize(fs, GlobalList.OnlineOrderNum);
fs.Close();
fs.Dispose();
///Write CSV File For Order
StringBuilder strBuilder = new StringBuilder();
TextWriter tw = new StreamWriter(#"C:\Web_Order\Order_W" + custordernum.ToString() + ".csv");
foreach (GridViewRow row in griditems.Rows)
{
foreach (TableCell cell in row.Cells)
{
// get cell's text
string cellText = cell.Text;
// add quotes and comma around value and append
strBuilder.Append("\"" + cellText + "\",");
}
strBuilder.Append("\n");
}
// output CSV result
tw.Write(strBuilder.ToString());
tw.Close();
tw.Dispose();
GlobalList.weborder = "W" + custordernum.ToString();
Response.Redirect("~/OrderSubmitted.aspx");
}
else
{
validatelbl.Text = "CANNOT SUBMIT FORM WITH ERRORS. PLEASE CORRECT YOUR ERRORS BEFORE SUBMITTING.";
validatelbl.Visible = true;
userlbl.Text = "Please correct your table with the correct information before submitting your order";
userlbl.Visible = true;
userlbl2.Text = "Are your Part Numbers correct? Are your Quantities in the correct format?";
userlbl2.Visible = true;
}
}
catch
{
//error message
}
}
Here's my edit/delete code for the GridView:
protected void griditems_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
griditems.PageIndex = e.NewPageIndex;
BindData();
}
protected void griditems_RowEditing(object sender, GridViewEditEventArgs e)
{
//Set the edit index.
griditems.EditIndex = e.NewEditIndex;
//Bind data to the GridView control.
BindData();
}
protected void griditems_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
//Reset the edit index.
griditems.EditIndex = -1;
//Bind data to the GridView control.
BindData();
}
protected void griditems_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
string valtext = "An error has occured, please check and make sure your editing is in the correct format and try again.";
orderbtn.Visible = false;
try
{
TextBox editpart = (TextBox)griditems.Rows[e.RowIndex].FindControl("partedit");
TextBox editqty = (TextBox)griditems.Rows[e.RowIndex].FindControl("qtyedit");
TextBox editshipto = (TextBox)griditems.Rows[e.RowIndex].FindControl("shiptoedit");
System.Web.UI.WebControls.Calendar editcal = (System.Web.UI.WebControls.Calendar)griditems.Rows[e.RowIndex].FindControl("reqdatecaledit");
DropDownList editshipmthd = (DropDownList)griditems.Rows[e.RowIndex].FindControl("shipmthdedit");
string newpart = editpart.Text.ToString();
int newqty = Convert.ToInt32(editqty.Text);
string newshipto = editshipto.Text.ToString();
string newreqdate = editcal.SelectedDate.ToShortDateString();
string newshipmthd = editshipmthd.SelectedItem.ToString();
//Reset date if calendar date is not changed so it is not null!
if (newreqdate == "1/1/0001")
newreqdate = reqdate;
DataTable dt = (DataTable)Session["table"];
DataRow dr = dt.Rows[e.RowIndex];
dr["Part Number"] = newpart;
dr["Quantity"] = newqty;
dr["Ship-TO"] = newshipto;
dr["Requested Date"] = newreqdate;
dr["Shipping Method"] = newshipmthd;
dr.AcceptChanges();
Session["table"] = dt;
if (validatelbl.Text == valtext)
validatelbl.Visible = false;
griditems.EditIndex = -1;
BindData();
orderbtn.Visible = true;
}
catch
{
validatelbl.Text = valtext;
validatelbl.Visible = true;
}
}
protected void griditems_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
try
{
//DataTable dt = table;
DataTable dt = (DataTable)Session["table"];
if (dt.Rows.Count > 0)
{
dt.Rows.RemoveAt(e.RowIndex + griditems.PageIndex * 10);
griditems.DataSource = dt;
BindData();
}
}
catch
{
validatelbl.Text = "An error occured while processing your request deleting a record. Please try again.";
validatelbl.Visible = true;
}
}
Here's the aspx code for the gridview:
<asp:GridView ID="griditems" runat="server"
onrowdeleting="griditems_RowDeleting" onrowediting="griditems_RowEditing" onrowupdating="griditems_RowUpdating"
AllowPaging="True"
onpageindexchanging="griditems_PageIndexChanging" Onrowcancelingedit="griditems_RowCancelingEdit"
Caption="Order Details" AutoGenerateDeleteButton="True"
AutoGenerateEditButton="True"
AutoGenerateColumns="False" >
<EditRowStyle BackColor="#FF9900" BorderStyle="Double"/>
<HeaderStyle Font-Bold="True" Font-Italic="False" />
<RowStyle HorizontalAlign="Center"/>
<Columns>
<asp:TemplateField HeaderText="Part Number">
<ItemTemplate>
<asp:Label ID = "partlbl" runat="server" Text='<%#Eval("Part Number") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="partedit" runat="server" Text='<%# Eval("Part Number")%>' ></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Quantity">
<ItemTemplate>
<asp:Label ID = "qtylbl" runat="server" Text='<%#Eval("Quantity") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="qtyedit" runat="server" Text='<%# Eval("Quantity")%>' ></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Ship-To">
<ItemTemplate>
<asp:Label ID = "shiptolbl" runat="server" Text='<%#Eval("Ship-To") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="shiptoedit" runat="server" Text='<%# Eval("Ship-To")%>' ></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Requested Date">
<ItemTemplate>
<asp:Label ID = "reqdatelbl" runat="server" Text='<%#Eval("Requested Date") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:Calendar ID="reqdatecaledit" runat="server" BackColor="White" BorderColor="#3366CC" BorderWidth="1px" CellPadding="1"
DayNameFormat="Shortest" Font-Names="Verdana" Font-Size="8pt" ForeColor="#003399" Height="200px" Width="220px"
ondayrender="reqdatecal_DayRender" ShowGridLines="True">
<DayHeaderStyle BackColor="#99CCCC" ForeColor="#336666" Height="1px" />
<DayStyle BackColor="White" />
<NextPrevStyle Font-Size="8pt" ForeColor="#CCCCFF" />
<OtherMonthDayStyle ForeColor="#999999" />
<SelectedDayStyle BackColor="#FF9900" Font-Bold="True" ForeColor="#CCFF99" />
<SelectorStyle BackColor="#99CCCC" ForeColor="#336666" />
<TitleStyle BackColor="#003399" BorderColor="#3366CC" BorderWidth="1px" Font-Bold="True" Font-Size="10pt" ForeColor="#CCCCFF"
Height="25px" />
<TodayDayStyle BackColor="#99CCCC" ForeColor="White" />
<WeekendDayStyle BackColor="#CCCCFF" /></asp:Calendar>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Shipping Method">
<ItemTemplate><asp:Label ID="shipmthdlbl" runat="server" Text='<%#Eval("Shipping Method") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList ID="shipmthdedit" runat="server">
<asp:ListItem>FedEx Ground (1-5 Business Days)</asp:ListItem>
<asp:ListItem>FedEx 3 Business Days</asp:ListItem>
<asp:ListItem>FedEx 2 Business Days</asp:ListItem>
<asp:ListItem>FedEx Overnight</asp:ListItem>
</asp:DropDownList>
</EditItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
I don't understand why it was working all this time and now all of the sudden it is not working. It creates the file with the new ordernumber as it should, its just the .csv file is empty (no data at all) Any thoughts?
You can correct your path, and replace TextWriter with StreamWriter
var path = Path.Combine("C:\Web_Order\Order_W",custordernum.ToString(),".csv");
StreamWriter tw = new StreamWriter(#path);
Or use directly var.
var tw = new StreamWriter(#path);
Adjust your code with try catch block in order to treat exception if occurs
try
{
}
catch(Exception ex)
{
Console.Write(ex.Message);
throw ex;
}
Not sure why you're using TextWriter here, and you don't need to redirect. Just write to Response.Write().
protected void btnDownload_Click(object sender, EventArgs e)
{
// No error so write as attachment
Response.ContentType = "text/csv";
Response.AddHeader("content-disposition", "attachment;filename=data.csv");
// Write your output here
Response.Write(...);
Response.End();
}

Categories