Custom pagination on itemtemplate using gridview - c#

I want to apply custom pagination to my gridview which contains itemtemplate
which has a image that comes from the database
I have tried with clientid mode static but that didnt work out
My Procedure:-
create procedure sp_BookingByPageSize
#pageNo int,
#NoOfRecord int,
#TotalRecord int output
as
select #TotalRecord =
count(*) from tblDiscount
select * from
(
select
Row_number() over
(order by r.bookingid asc)
as RowNo,
r.BookingId,
u.Fullname,
h.hotelName,
case when r.bookingstatus=1 then 'Confirmed'
when r.BookingStatus=0 then 'Cancelled'
end as Booking_Status
,r.Check_In,r.Check_Out,r.NoOfGuests,ro.RoomTypeName,r.NoOfRoomsBooked,r.NationalID,r.Amount from tblReservation as r inner join
tblHotel as h on r.HotelId=h.HotelID
inner join tblUser as u
on u.UId=r.UId inner join tblRooms as ro on ro.RoomsID=r.RoomType)
AS Tab
where tab.RowNo between((#PageNo-1)*#NoOfRecord)+1 and (#PageNo*#NoOfRecord)
order by 2 asc
return
My aspx file:
<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:GridView ID="GridView1" CssClass="table table-condensed" runat="server" OnRowCommand="GridView1_RowCommand" DataKeyNames="bookingid" AutoGenerateColumns="false">
<AlternatingRowStyle BackColor="White" ForeColor="#284775"></AlternatingRowStyle>
<Columns>
<asp:ButtonField CommandName="download"
ControlStyle-CssClass="btn btn-info" ButtonType="Button"
Text="Download Invoice" HeaderText="Invoice" />
<asp:BoundField DataField="bookingid" HeaderText="Booking ID" />
<asp:BoundField DataField="hotelName" HeaderText="Hotel Name" />
<asp:BoundField DataField="Booking_Status" HeaderText="Booking Status" />
<asp:BoundField DataField="Check_In" HeaderText="Check In" />
<asp:BoundField DataField="Check_Out" HeaderText="Check Out" />
<asp:BoundField DataField="RoomTypeName" HeaderText="Room Type" />
<asp:BoundField DataField="NoOfRoomsBooked" HeaderText="No of Rooms Booked" />
<asp:BoundField DataField="Amount" HeaderText="Amount" />
<asp:TemplateField HeaderText="NationalID">
<ItemTemplate>
<asp:Image ID="Image1" CssClass="default" runat="server"
ImageUrl='<%# "data:Image/jpg;base64,"
+ Convert.ToBase64String((byte[])Eval("NationalID")) %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:HiddenField runat="server" ID="hiddenprimary" />
<div style="margin-left: 1500px;">
<asp:Panel ID="Panel1" runat="server"></asp:Panel>
</div>
MyCode behinde:-
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using HotelBAL;
namespace HotelReservation.Views
{
public partial class AdminViewBooking : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
PopulateData(1, 5);
}
AddpaggingButton();
}
private void PopulateData(int pageNo, int noOfRecord)
{
GridView1.DataSource = BookingBal.PopulateData(pageNo, noOfRecord);
GridView1.DataBind();
ViewState["TotalRecord"] = BookingBal.getTotalRecord1();
ViewState["NoOfRecord"] = BookingBal.getNoOfRecord1();
}
private void AddpaggingButton()
{
int totalRecord = 0;
int noOfRecord = 0;
totalRecord = ViewState["TotalRecord"] != null ? (int)ViewState["TotalRecord"] : 0;
noOfRecord = ViewState["NoOfRecord"] != null ? (int)ViewState["NoOfRecord"] : 0;
int pages = 0;
if (totalRecord > 0 && noOfRecord > 0)
{
pages = (totalRecord / noOfRecord) + ((totalRecord % noOfRecord) > 0 ? 1 : 0);
for (int i = 0; i < pages; i++)
{
Button b = new Button();
b.Text = (i + 1).ToString();
b.CommandArgument = (i + 1).ToString();
b.ID = "Button_" + (i + 1).ToString();
b.CssClass = "btn btn-outline-warning";
b.Click += new EventHandler(this.b_click);
Panel1.Controls.Add(b);
}
}
}
private void b_click(object sender, EventArgs e)
{
//this is for get data from database from clicking button
string pageNo = ((Button)sender).CommandArgument;
PopulateData(Convert.ToInt32(pageNo), 5);
}
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
}
}
}
Here b_click should work but it is not working any help would be appreciated as I am new to this custom paging

I myself solved the problem by using a generic handler
<ContentTemplate>
<asp:GridView ID="GridView1" CssClass="table table-condensed" runat="server" OnRowCommand="GridView1_RowCommand" DataKeyNames="bookingid" AutoGenerateColumns="false">
<AlternatingRowStyle BackColor="White" ForeColor="#284775"></AlternatingRowStyle>
<Columns>
<asp:ButtonField CommandName="download"
ControlStyle-CssClass="btn btn-info" ButtonType="Button"
Text="Download Invoice" HeaderText="Invoice" />
<asp:BoundField DataField="bookingid" HeaderText="Booking ID" />
<asp:BoundField DataField="hotelName" HeaderText="Hotel Name" />
<asp:BoundField DataField="Booking_Status" HeaderText="Booking Status" />
<asp:BoundField DataField="Check_In" HeaderText="Check In" />
<asp:BoundField DataField="Check_Out" HeaderText="Check Out" />
<asp:BoundField DataField="RoomTypeName" HeaderText="Room Type" />
<asp:BoundField DataField="NoOfRoomsBooked" HeaderText="No of Rooms Booked" />
<asp:BoundField DataField="Amount" HeaderText="Amount" />
<asp:BoundField HeaderText="Image" DataField="NationalID" Visible="false" />
<asp:TemplateField HeaderText="NationalID" >
<ItemTemplate>
<asp:Image ID="Image1" runat="server" ImageUrl='<%# "imageHandler.ashx?bookingId="+ Eval("bookingId") %>'
Height="150px" Width="150px" />
<%-- <asp:Image ID="Image1" CssClass="default" runat="server"
ImageUrl='<%# "data:Image/jpg;base64,"
+ Convert.ToBase64String((byte[])Eval("NationalID")) %>' />--%>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:HiddenField runat="server" ID="hiddenprimary" />
<div style="margin-left: 1500px;">
<asp:Panel ID="Panel1" runat="server"></asp:Panel>
</div>
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
namespace HotelReservation.Views
{
/// <summary>
/// Summary description for ImageHandler
/// </summary>
public class ImageHandler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
string imageid = context.Request.QueryString["bookingId"];
using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["MyProjectConnection"].ConnectionString))
{
connection.Open();
SqlCommand command = new SqlCommand("select NationalID from tblReservation where bookingid=" + imageid, connection);
command.CommandType = CommandType.Text;
SqlDataReader dr = command.ExecuteReader();
dr.Read();
context.Response.BinaryWrite((Byte[])dr[0]);
connection.Close();
context.Response.End();
}
}
public bool IsReusable
{
get
{
return false;
}
}
}
}

Related

Handling Multiple GridViews in ASP.Net and C#

I Have a Table column Called Status which takes three Values 1, 2 or 3. Now, I want to Display another column Name1 in either of the three GridViews depending on the Status. Also I have link buttons which Redirect to different web forms.
This is the output I'm Getting. The ID of this GridView is GridView1
This is the code I've used
Markup:
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Admin.aspx.cs" Inherits="Default2" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title></title>
<style type="text/css">
body{
font-family:Arial;
font-size:10px;
}
td,th{
height:25px;
width:100Px;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<div>
<hr />
<asp:GridView ID="GridView" runat="server" HeaderStyle-BackColor="#3AC0F2" HeaderStyle-ForeColor="White"
RowStyle-BackColor="#A1DCF2" AlternatingRowStyle-BackColor="White" AlternatingRowStyle-ForeColor="#000"
AutoGenerateColumns="false" Height="225px" Width="368px"
>
<Columns>
<asp:BoundField DataField="Name1" HeaderText="File Name" />
<asp:BoundField DataField="Status" HeaderText="Status" />
<asp:TemplateField ItemStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:LinkButton ID="lnkEdit" runat="server" HeaderText="Edit Status" Text="Edit Application" OnClick="EditFile"
CommandArgument='<%# Eval("Status") %>'></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:GridView ID="GridView1" runat="server" HeaderStyle-BackColor="#3AC0F2" HeaderStyle-ForeColor="White"
RowStyle-BackColor="#A1DCF2" AlternatingRowStyle-BackColor="White" AlternatingRowStyle-ForeColor="#000"
AutoGenerateColumns="false" Height="225px" Width="368px"
>
<Columns>
<asp:BoundField DataField="Name1" HeaderText="File Name" />
<asp:BoundField DataField="Status" HeaderText="Status" />
<asp:TemplateField ItemStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:LinkButton ID="lnkEdit" runat="server" HeaderText="Edit Status" Text="Edit Application" OnClick="EditFile1"
CommandArgument='<%# Eval("Status") %>'></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:GridView ID="GridView2" runat="server" HeaderStyle-BackColor="#3AC0F2" HeaderStyle-ForeColor="White"
RowStyle-BackColor="#A1DCF2" AlternatingRowStyle-BackColor="White" AlternatingRowStyle-ForeColor="#000"
AutoGenerateColumns="false" Height="225px" Width="368px"
>
<Columns>
<asp:BoundField DataField="Name1" HeaderText="File Name" />
<asp:BoundField DataField="Status" HeaderText="Status" />
<asp:TemplateField ItemStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:LinkButton ID="lnkEdit" runat="server" HeaderText="Edit Status" Text="Edit Application"
CommandArgument='<%# Eval("Status") %>'></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
</form>
</body>
</html>
C#
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.IO;
using System.Data.SqlClient;
public partial class Default2 : System.Web.UI.Page
{
String statusVariable= string.Empty;
protected void Page_Load(object sender, EventArgs e)
{
//lb1.Text = "<b><font color=Brown>" + "WELLCOME ADMIN:: " + "</font>" + "<b><font color=red>" + Session["name"] + "</font>";
if (!IsPostBack)
{
BindGrid();
}
}
private void BindGrid()
{
DataTable dt;
string constr = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = "Select Name1,Status from TBL_MST_ALL2";
cmd.Connection = con;
con.Open();
using (SqlDataReader reader = cmd.ExecuteReader())
{
{
while (reader.Read())
{
if (reader["Status"].ToString() == "3")
{
GridView.DataSource = reader;
GridView.DataBind();
}
else if (reader["Status"].ToString() == "2")
{
GridView1.DataSource = reader;
GridView1.DataBind();
}
else if (reader["Status"].ToString() == "1")
{
GridView1.DataSource = reader;
GridView1.DataBind();
}
}
con.Close();
}
}
}
}
}
protected void EditFile(object sender, EventArgs e)
{
Response.Redirect("EditResume.aspx");
}
protected void EditFile1(object sender, EventArgs e)
{
Response.Redirect("EditResume1.aspx");
}
}
However, all the data is being displayed in GridView1 regardless of the Status.

How to fetch data from a column of a gridview and perform arithmetic operations on the column?

I am working on a Cart project, and using Visual Studio 2010 with SQL server express. I am using a Gridview to display data from my cart table in my database. I have a product table in my database , and I insert products from product table to the cart table . after that i display the cart in the gridview. the problem I am facing is i cannot use the Price column from my gridview to add the prices of the items in the cart to display the total price of the order. how can i do that?
my asp gridview source code is as follows
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
CellPadding="4" CssClass="table table-condensed" DataSourceID="SqlDataSource1"
ForeColor="#333333" GridLines="None"
onselectedindexchanged="GridView1_SelectedIndexChanged"
DataKeyNames="serial_no" onrowdatabound="GridView1_RowDataBound">
<AlternatingRowStyle BackColor="White" />
<Columns>
<asp:TemplateField HeaderText="serial_no" InsertVisible="False"
SortExpression="serial_no">
<EditItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Eval("serial_no") %>'></asp:Label>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Bind("serial_no") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="Name" HeaderText="Name"
SortExpression="Name" ControlStyle-CssClass="cart_menu" >
</asp:BoundField>
<asp:BoundField DataField="Quantity" HeaderText="Quantity"
SortExpression="Quantity" />
<asp:BoundField DataField="Price" HeaderText="Price"
SortExpression="Price" />
<asp:TemplateField HeaderText="Delete" SortExpression="serial_no">
<EditItemTemplate>
<asp:Label ID="Label2" runat="server" Text='<%# Eval("serial_no") %>'></asp:Label>
</EditItemTemplate>
<ItemTemplate>
<asp:Button ID="Button1" runat="server" CommandName="Delete"
onclick="Button1_Click1" Text="Button" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
<FooterStyle BackColor="#FF7800" Font-Bold="True" ForeColor="White" CssClass="cart_menu" />
<HeaderStyle BackColor="#FF7800" Font-Bold="True" ForeColor="White" CssClass="cart_menu" />
<PagerStyle BackColor="#FFCC66" ForeColor="#333333" HorizontalAlign="Center" />
<RowStyle BackColor="#FFFFFF" ForeColor="#333333" />
<SelectedRowStyle BackColor="#FFCC66" Font-Bold="True" ForeColor="Navy" />
<SortedAscendingCellStyle BackColor="#FDF5AC" />
<SortedAscendingHeaderStyle BackColor="#4D0000" />
<SortedDescendingCellStyle BackColor="#FCF6C0" />
<SortedDescendingHeaderStyle BackColor="#820000" />
</asp:GridView>
my sqldatasource
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:cs %>"
ProviderName="<%$ ConnectionStrings:cs.ProviderName %>"
SelectCommand="SELECT cartdemo.serial_no, Product.Name, Product.P_Image, Product.Price, cartdemo.Quantity FROM cartdemo INNER JOIN Product ON cartdemo.ProductID = Product.ProductID WHERE (cartdemo.CID = #cid)"
DeleteCommand="DELETE FROM cartdemo WHERE (serial_no = #sl_no)">
<DeleteParameters>
<asp:Parameter Name="sl_no" />
</DeleteParameters>
<SelectParameters>
<asp:SessionParameter Name="cid" SessionField="ssid" />
</SelectParameters>
</asp:SqlDataSource>
my c# code behind
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Collections;
using System.Data.SqlClient;
using System.Data;
using System.Configuration;
public partial class cart2 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
}
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
GridViewRow grd = e.Row;
switch (grd.RowType)
{
case DataControlRowType.DataRow:
{
Button btn = (Button)grd.FindControl("Button1");
if (btn != null)
{
Label lbl_pid = (Label)grd.FindControl("Label1");
btn.CommandArgument = lbl_pid.Text;
}
break;
}
}
calTotal(4);
}
protected void Button1_Click1(object sender, EventArgs e)
{
Button btn = sender as Button;
string id = btn.CommandArgument;
SqlDataSource1.DeleteParameters[0].DefaultValue = id;
SqlDataSource1.Delete();
GridView1.DataBind();
}
public void calTotal(int curCol)
{
decimal valueColumn = 0;
//try
//{
foreach (GridViewRow row in GridView1.Rows)
{
valueColumn = valueColumn + Convert.ToDecimal(row.Cells[curCol].Text);
}
//}
//catch(Exception r)
//{
//}
Label3.Text = "Rs." + valueColumn.ToString();
}
}
If I am understanding your question correctly, what you are wanting to know about is the SQL function "SUM". You can find more information about sum here. The short version is that SUM returns the total for a column of NUMERIC data. The basic syntax looks something like this:
SELECT SUM(myColumn)
FROM myTable;
/* Assume myColumn contains {0, 1, 2, 3, 4, 5} */
/* The output of this SELECT statement would be {15} */

PagerTemplate in gridview not working properly

I am not getting the point why this is happening.
I have a Gridview, inside that I have implemented a pagerTemplate. It is showing me the correct records which are coming from the database.
First of All, I took the logic of implementing the gridview pager part from here. And I implemented the same as described their.
Now the scenario which I came up with is that, When I change the dropdown selection, my gridview gets postback and all the Row of the grid gets disturbed. I dont know why this is happening.
See the code which I implemented:-
<asp:GridView ID="grdCSRPageData" runat="server" Width="100%" border="1" Style="border: 1px solid #E5E5E5;" CellPadding="3"
AutoGenerateColumns="False" OnDataBound="grdCSRPageData_DataBound" AllowPaging="true" CssClass="hoverTable" EmptyDataText="No Records Found"
OnPageIndexChanging="grdCSRPageData_PageIndexChanging" DataKeyNames="Id" OnRowDeleting="grdCSRPageData_RowDeleting"
PageSize="4" ShowFooter="true" OnRowEditing="grdCSRPageData_RowEditing" OnRowUpdating="grdCSRPageData_RowUpdating"
OnRowCancelingEdit="grdCSRPageData_RowCancelingEdit">
<AlternatingRowStyle CssClass="k-alt" BackColor="#f5f5f5" />
<Columns>
<asp:TemplateField HeaderText="Select" HeaderStyle-Width="5%" HeaderStyle-CssClass="k-grid td">
<ItemTemplate>
<asp:CheckBox ID="chkSelect" runat="server" AutoPostBack="false" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="page_title" HeaderText="Page Title" ItemStyle-Width="30" HeaderStyle-CssClass="k-grid td" />
<asp:BoundField DataField="page_description" HeaderText="Page Description" ItemStyle-Width="30" HeaderStyle-CssClass="k-grid td" />
<asp:BoundField DataField="meta_title" HeaderText="Meta Title" ItemStyle-Width="30" HeaderStyle-CssClass="k-grid td" />
<asp:BoundField DataField="meta_keywords" HeaderText="Meta Keywords" ItemStyle-Width="30" HeaderStyle-CssClass="k-grid td" />
<asp:BoundField DataField="meta_description" HeaderText="Meta Description" ItemStyle-Width="30" HeaderStyle-CssClass="k-grid td" />
<asp:BoundField DataField="Active" HeaderText="Active" ItemStyle-Width="30" HeaderStyle-CssClass="k-grid td" />
<asp:TemplateField HeaderText="Action" HeaderStyle-Width="15%" HeaderStyle-CssClass="k-grid td">
<ItemTemplate>
<asp:ImageButton ID="btnDelete" AlternateText="Delete" ImageUrl="~/images/delete.png" runat="server" Width="15" Height="15" CommandName="Delete" CommandArgument='<%# Eval("Id") %>' CausesValidation="false" OnClientClick="return confirm('Are you sure you want to delete this record?')" />
</ItemTemplate>
</asp:TemplateField>
<asp:CommandField ButtonType="Image" ItemStyle-Width="15" EditImageUrl="~/images/edit.png" ShowEditButton="True" ControlStyle-Width="15" ControlStyle-Height="15" CancelImageUrl="~/images/close.png" UpdateImageUrl="~/images/update.png">
<ControlStyle Height="20px" Width="20px"></ControlStyle>
</asp:CommandField>
</Columns>
<pagerstyle />
<pagerTemplate>
<table style="width:100%">
<tr>
<td>
<asp:label id="MessageLabel" Text="Select a page:" runat="server"/>
<asp:dropdownlist id="PageDropDownList" AutoPostBack="true" OnSelectedIndexChanged="PageDropDownList_SelectedIndexChanged"
runat="server"/>
<td style="width:70%; text-align:right">
<asp:label id="CurrentPageLabel" runat="server"/>
</td>
</td>
</tr>
</table>
</pagerTemplate>
</asp:GridView>
The code is added with PagerTemplate. Also see my code behind as given their:-
Cs Code for the PagerTemplate:-
protected void grdCSRPageData_DataBound(object sender, EventArgs e)
{
GridViewRow pagerRow = grdCSRPageData.BottomPagerRow;
DropDownList pageList = (DropDownList)pagerRow.Cells[0].FindControl("PageDropDownList");
Label pageLabel = (Label)pagerRow.Cells[0].FindControl("CurrentPageLabel");
if (pageList != null)
{
for (int i = 0; i < grdCSRPageData.PageCount; i++)
{
int pageNumber = i + 1;
ListItem item = new ListItem(pageNumber.ToString());
if (i == grdCSRPageData.PageIndex)
{
item.Selected = true;
}
pageList.Items.Add(item);
}
}
if (pageLabel != null)
{
int currentPage = grdCSRPageData.PageIndex + 1;
pageLabel.Text = "Page " + currentPage.ToString() +
" of " + grdCSRPageData.PageCount.ToString();
}
}
protected void PageDropDownList_SelectedIndexChanged(object sender, EventArgs e)
{
GridViewRow pagerRow = grdCSRPageData.BottomPagerRow;
DropDownList pagelist = (DropDownList)pagerRow.Cells[0].FindControl("PageDropDownList");
grdCSRPageData.PageIndex = pagelist.SelectedIndex;
}
Please help. Any help would be appreciable
try changing the AutoPostBack="true" to false of your dropDownList and be sure to load data in Page_Load inside
if (!IsPostBack){
//bind gridview
}
update
try inserting your dropDownList (with AutoPostBack="true") and your GridView inside an UpdatePanel with "UpdateMode=Conditional" like this
<asp:UpdatePanel runat="server" ID="up1" UpdateMode="Conditional">
<ContentTemplate>
//put here gridview
<ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="PageDropDownList" EventName="SelectedIndexChanged" />
</Triggers>
</asp:UpdatePanel>
update
try this solution with your code
aspx page
<asp:GridView ID="grdUser"
AllowPaging="true"
AutoGenerateColumns="False"
OnDataBound="grdUser_DataBound"
OnRowDeleting="grdUser_RowDeleting"
OnPreRender="PreRenderGrid"
runat="server"
Width="100%"
border="1"
DataKeyNames="Id"
PageSize="2"
OnPageIndexChanging="grdUser_PageIndexChanging"
EnableSortingAndPagingCallbacks="false"
CssClass="pagi" OnRowCommand="grdUser_RowCommand">
<Columns>
<asp:TemplateField HeaderText="Select" ItemStyle-Width="30" HeaderStyle-CssClass="k-grid td">
<ItemTemplate>
<asp:CheckBox ID="chkDelete" runat="server" />
</ItemTemplate>
<HeaderStyle CssClass="k-grid td"></HeaderStyle>
<ItemStyle Width="30px"></ItemStyle>
</asp:TemplateField>
<asp:BoundField DataField="username" HeaderText="UserName" ItemStyle-Width="30" HeaderStyle-CssClass="k-grid td">
<HeaderStyle CssClass="k-grid td"></HeaderStyle>
<ItemStyle Width="30px"></ItemStyle>
</asp:BoundField>
<asp:BoundField DataField="email" HeaderText="Email Id" ItemStyle-Width="30" HeaderStyle-CssClass="k-grid td">
<HeaderStyle CssClass="k-grid td"></HeaderStyle>
<ItemStyle Width="30px"></ItemStyle>
</asp:BoundField>
<asp:BoundField DataField="usertype" HeaderText="UserType" ItemStyle-Width="30" HeaderStyle-CssClass="k-grid td">
<HeaderStyle CssClass="k-grid td"></HeaderStyle>
<ItemStyle Width="30px"></ItemStyle>
</asp:BoundField>
<asp:BoundField DataField="active" HeaderText="Active" ItemStyle-Width="30" HeaderStyle-CssClass="k-grid td">
<HeaderStyle CssClass="k-grid td"></HeaderStyle>
<ItemStyle Width="30px"></ItemStyle>
</asp:BoundField>
<asp:TemplateField HeaderText="Action" HeaderStyle-Width="5%" ItemStyle-Width="20" HeaderStyle-CssClass="k-grid td">
<ItemTemplate>
<asp:ImageButton ID="btnDelete" AlternateText="Delete" ImageUrl="~/images/delete.png" runat="server" Width="15" Height="15" CommandName="eEdit" CommandArgument='<%# Eval("Id") %>' CausesValidation="false" OnClientClick="return confirm('Are you sure you want to delete this record?')" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:ImageButton ID="btnEdit" AlternateText="Edit" ImageUrl="~/images/edit.png" runat="server" Width="15" Height="15" CommandName="eEdit" CommandArgument='<%# Eval("Id") %>' CausesValidation="false" />
</ItemTemplate>
<HeaderStyle CssClass="k-grid td" Width="15%"></HeaderStyle>
<ItemStyle Width="30px"></ItemStyle>
</asp:TemplateField>
</Columns>
<PagerStyle ForeColor="#e3e3e3"
BackColor="#e3e3e3" CssClass="grid-pagi" />
<PagerTemplate>
<table runat="server" id="testTable1" style="width: 100%" class="k-grid td">
<tr>
<td class="col-md-7 pull-left">
<asp:Label ID="MessageLabel"
Text="Select a page:"
runat="server" />
<asp:LinkButton ID="FirstLB" runat="server" CommandName="Page" CommandArgument="First" ToolTip="First" CssClass="btn-pager btn-default"><<</asp:LinkButton>
<asp:LinkButton ID="PrevLB" runat="server" CommandName="Page" CommandArgument="Prev" ToolTip="Previous" CssClass="btn-pager btn-default"><</asp:LinkButton>
<asp:DropDownList runat="server" ID="PageDropDownList" AutoPostBack="true" EnableViewState="true" OnSelectedIndexChanged="PageDropDownList_SelectedIndexChanged" CssClass="selectpicker form-control-drp"></asp:DropDownList>
<asp:LinkButton ID="NextLB" runat="server" CommandName="Page" CommandArgument="Next" ToolTip="Next" CssClass="btn-pager btn-default">></asp:LinkButton>
<asp:LinkButton ID="LastLB" runat="server" CommandName="Page" CommandArgument="Last" ToolTip="Last" CssClass="btn-pager btn-default">>></asp:LinkButton>
</td>
<td class="col-md-3 pull-right">
<asp:Label ID="PageSizeLabel" runat="server" Text="Select Page Size: "></asp:Label>
<asp:DropDownList ID="ddlPageSize" runat="server" OnSelectedIndexChanged="ddlPageSize_SelectedIndexChanged" AutoPostBack="true" CssClass="selectpicker form-control-drp">
<%-- <asp:ListItem Value="0" Text="0" />--%>
<asp:ListItem Value="1" Text="1" />
<asp:ListItem Value="2" Text="2" />
<asp:ListItem Value="3" Text="3" />
</asp:DropDownList>
</td>
<td class="col-md-2">
<asp:Label ID="CurrentPageLabel" runat="server" />
</td>
</tr>
</table>
</PagerTemplate>
</asp:GridView>
code behind
protected void grdUser_DataBound(object sender, EventArgs e)
{
GridViewRow pagerRow = grdUser.BottomPagerRow;
DropDownList pageSizeList = (DropDownList)pagerRow.Cells[0].FindControl("ddlPageSize");
if (Context.Session["PageSize"] != null)
{
pageSizeList.SelectedValue = Context.Session["PageSize"].ToString();
}
DropDownList pageList = (DropDownList)pagerRow.Cells[0].FindControl("PageDropDownList");
Label pageLabel = (Label)pagerRow.Cells[0].FindControl("CurrentPageLabel");
if (pageList != null)
{
for (int i = 0; i < grdUser.PageCount; i++)
{
int pageNumber = i + 1;
ListItem item = new ListItem(pageNumber.ToString());
if (i == grdUser.PageIndex)
{
item.Selected = true;
}
pageList.Items.Add(item);
}
}
if (pageLabel != null)
{
int currentPage = grdUser.PageIndex + 1;
pageLabel.Text = "View " + currentPage.ToString() + " of " + grdUser.PageCount.ToString();
}
}
protected void ddlPageSize_SelectedIndexChanged(object sender, EventArgs e)
{
GridViewRow pagerRow = grdUser.BottomPagerRow;
DropDownList pageSizeList = (DropDownList)pagerRow.Cells[0].FindControl("ddlPageSize");
//
grdUser.PageSize = Convert.ToInt32(pageSizeList.SelectedValue);
Context.Session["PageSize"] = pageSizeList.SelectedValue;
BindGrid();
}
protected void PageDropDownList_SelectedIndexChanged(object sender, EventArgs e)
{
GridViewRow pagerRow = grdUser.BottomPagerRow;
DropDownList pageList = (DropDownList)pagerRow.Cells[0].FindControl("PageDropDownList");
grdUser.PageIndex = pageList.SelectedIndex;
BindGrid();
}
protected void PreRenderGrid(object sender, EventArgs e)
{
GridViewRow pagerRow = grdUser.BottomPagerRow;
DropDownList pageList = (DropDownList)pagerRow.Cells[0].FindControl("PageDropDownList");//error
Label pageLabel = (Label)pagerRow.Cells[0].FindControl("CurrentPageLabel");
if (pageList != null)
{
for (int i = 0; i < grdUser.PageCount; i++)
{
int pageNumber = i + 1;
ListItem item = new ListItem(pageNumber.ToString());
if (i == grdUser.PageIndex)
{
item.Selected = true;
}
pageList.Items.Add(item);
}
}
if (pageLabel != null)
{
int currentPage = grdUser.PageIndex + 1;
pageLabel.Text = "View " + currentPage.ToString() + " of " + grdUser.PageCount.ToString();
}
this.grdUser.Controls[0].Controls[this.grdUser.Controls[0].Controls.Count - 1].Visible = true;
BindGrid();
}

Visual Studio 12 - Gridview inserting footer row on submit

I have a gridview that I need a footer row inserted with the data from a textbox when the user hits submit. I have tried over and over and I can not get past the following error:
Object reference not set to an instance of an object. The error is flagged on the Textbox AddName line of code in the code behind.
Here is my code:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Admin.aspx.cs" Inherits="WorkOrder.Admin" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<link href="Style.css" rel="stylesheet" type="text/css" />
<link href="msgBoxLight.css" rel="stylesheet" type="text/css" />
<script src="Scripts/jquery-1.8.0.min.js" type="text/javascript"></script>
<script src="Scripts/jquery.msgBox.js" type="text/javascript"></script>
</head>
<body>
<form id="form2" runat="server">
<div>
<asp:Panel ID="Panel1" runat="server" Width="1020px">
<asp:Image ID="Image1" runat="server" ImageUrl="~/Images/mast_left.png" />
</asp:Panel>
</div>
<div class="Section"> <hr /><h2>
Online Work Order Form - (Admin)</h2>
</div>
<br />
<asp:Label ID="Label2" runat="server" Text="Select data you want to view and click the submit button:" CssClass="label"></asp:Label><br /><br />
<div>
<asp:GridView ID="GridViewAdmin" runat="server" AutoGenerateColumns="False" AutoGenerateEditButton="True" DataSourceID="SqlDataSource1" DataKeyNames="WO_ID" EnableModelValidation="True"
>
<Columns>
<asp:BoundField DataField="WO_ID" HeaderText="WO_ID" ReadOnly="True" SortExpression="WO_ID" />
<asp:BoundField DataField="Name" HeaderText="Name" ReadOnly="True" SortExpression="Name" />
<asp:BoundField DataField="Job_Title" HeaderText="Job_Title" ReadOnly="True" SortExpression="Job_Title" />
<asp:BoundField DataField="Job_Assigned_To" HeaderText="Job_Assigned_To" SortExpression="Job_Assigned_To" />
<asp:CheckBoxField DataField="Completed" HeaderText="Completed" SortExpression="Completed" />
<asp:BoundField DataField="Completed_Date" HeaderText="Completed_Date" SortExpression="Completed_Date" />
<asp:BoundField DataField="Notes" HeaderText="Notes" SortExpression="Notes" />
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:ZSC_WorkOrdersConnectionString %>"
SelectCommand="SELECT [WO_ID], [Name], [Job_Type], [Job_UpdateName], [Job_Title], [Job_Description], [Job_Assigned_To], [Completed], [Completed_Date], [Notes] FROM [WO_Submission_Details]"
UpdateCommand="UPDATE [WO_Submission_Details] SET [Job_Assigned_To] = #Job_Assigned_To, [Completed] = #Completed, [Completed_Date] = #Completed_Date, [Notes] = #Notes WHERE [WO_ID] = #WO_ID">
</asp:SqlDataSource>
</div>
<br /> <asp:HyperLink ID="HyperLink1" runat="server" NavigateUrl="~/AdminReport.aspx">Work Order Report</asp:HyperLink>
<br />
<br />
<hr />
<br />
<asp:Label ID="Label1" runat="server" Text="Enter name below to add to Marketing employee table" CssClass="label"></asp:Label>
<br />
<br />
<asp:Label ID="Label3" runat="server" Text="Name:" CssClass="label"></asp:Label>
<asp:TextBox ID="txtAddName" runat="server" Width="170px"></asp:TextBox><br /><br />
<asp:Label ID="Label4" runat="server" Text="Email:" CssClass="label"></asp:Label>
<asp:TextBox ID="txtAddEmail" runat="server" Width="170px"></asp:TextBox>
<br /><br />
<asp:Button ID="btnSubmit" runat="server" Text="Submit" OnClick="btnSubmit_Click" />
<br /><br />
<asp:GridView ID="GridViewStaff" runat="server"
AutoGenerateColumns="False"
AutoGenerateDeleteButton="True"
BackColor="White" BorderColor="#3366CC"
BorderStyle="None" BorderWidth="1px" CellPadding="5"
DataSourceID="SqlDataSource2" datakeynames="ID" AllowSorting="True">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:Label runat="server" Text='<%#Eval("Name") %>' />
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtAddName" runat="server" Width="170px"></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:Label runat="server" text='<%#Eval("Email")%>'/>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtAddEmail" runat="server" Width="170px"></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
</Columns>
<FooterStyle BackColor="#99CCCC" ForeColor="#003399" />
<HeaderStyle BackColor="#003399" Font-Bold="True" ForeColor="#CCCCFF" />
<PagerStyle BackColor="#99CCCC" ForeColor="#003399" HorizontalAlign="Left" />
<RowStyle BackColor="White" ForeColor="#003399" />
<SelectedRowStyle BackColor="#009999" Font-Bold="True" ForeColor="#CCFF99" />
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource2" runat="server"
ConnectionString="<%$ ConnectionStrings:ZSC_WorkOrdersConnectionString %>"
SelectCommand="SELECT * FROM [Marketing_Staff]" InsertCommand="INSERT INTO [Marketing_Staff] ([Name], [Email]) VALUES (#Name, #Email)">
<InsertParameters>
<asp:Parameter Type="String" Name="Name"></asp:Parameter>
<asp:Parameter Type="String" Name="Email"></asp:Parameter>
</InsertParameters>
</asp:SqlDataSource>
</form>
</body>
</html>
Code behind:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Drawing.Design;
using System.Data;
using System.Data.SqlClient;
using System.Data.Sql;
using System.Text;
using System.IO;
namespace WorkOrder
{
public partial class Admin : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
bindgridView();
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
TextBox AddName = GridViewStaff.FooterRow.FindControl("txtAddName") as TextBox;
// Response.Write(AddName.Text);
//TextBox Email = GridViewStaff.FooterRow.FindControl("txtAddEmail") as TextBox;
SqlDataSource2.InsertParameters["Name"].DefaultValue = txtAddName.Text;
// SqlDataSource2.InsertParameters["Email"].DefaultValue = txtAddEmail.Text;
SqlDataSource2.Insert();
// ExecuteInsert(txtAddName.Text);
txtAddName.Text = "";
txtAddEmail.Text = "";
}
public string GetConnectionString()
{
//sets the connection string from your web config file "ConnString" is the name of your Connection String
return System.Configuration.ConfigurationManager.ConnectionStrings["ZSC_WorkOrdersConnectionString"].ConnectionString;
}
public void bindgridView()
{
try
{
SqlConnection conn = new SqlConnection(GetConnectionString());
string query = "Select * WO_ID, Name, Job_Type, Job_UpdateName, Job_Title, Job_Description, Job_Assigned_To, Completed, Completed_Date, Notes FROM WO_Submission_Details";
DataSet ds = new DataSet();
SqlDataAdapter sqldt = new SqlDataAdapter(query, conn);
sqldt.Fill(ds);
GridViewAdmin.DataSource = ds;
GridViewAdmin.DataBind();
if (ViewState["delRows"] != null)
{
int[] delIndices = (int[])ViewState["delRows"];
int itemsLength = delIndices.Count(indx => indx != 0);
//create the javascript array in the client side
//push the deleted row indexes from c# array to javascript array
StringBuilder sb = new StringBuilder();
sb.Append("<script>");
sb.Append("var indexArray = new Array;");
for (int i = 0; i < itemsLength; i++)
{
sb.Append("indexArray.push('" + delIndices[i] + "');");
}
sb.Append("</script>");
ClientScript.RegisterStartupScript(this.GetType(), "arrayScript", sb.ToString());
//call the deleteRow function on the client side
this.ClientScript.RegisterStartupScript(typeof(Page), "del", "javascript:deletegrdvwRow()", true);
}
}
catch (Exception)
{ }
}
protected void GridViewAdmin_RowEditing(object sender, GridViewEditEventArgs e)
{
GridViewAdmin.EditIndex = e.NewEditIndex;
}
protected void GridViewAdmin_RowCancelingEdit(object sender, EventArgs e)
{
GridViewAdmin.EditIndex = -1;
}
protected void GridViewAdmin_RowCreated(object sender, GridViewRowEventArgs e)
{
foreach (TableCell cell in e.Row.Cells)
{
if (!string.IsNullOrEmpty(cell.Text) && cell.Text != " ")
{
BoundField field = (BoundField)((DataControlFieldCell)cell).ContainingField;
if ((field.DataField != "Job_Assigned_To") && (field.DataField != "Completed") && (field.DataField != "Completed_Date") && (field.DataField != "Notes"))
field.ReadOnly = true;
}
}
}
protected void GridViewAdmin_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
try
{
GridViewAdmin.PageIndex = e.NewPageIndex;
//while moving to the next page, clear the viewstate
ViewState["delRows"] = null;
}
catch (Exception)
{ }
}
protected void GridViewAdmin_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
try
{
GridViewRow row = (GridViewRow)GridViewAdmin.Rows[e.RowIndex];
//i set datakeys="ProductName,ProductID" in gridview in aspx page
//datakeys[rowindex][1]->refers to productid which is primary key.
string WOID = GridViewAdmin.DataKeys[row.RowIndex][0].ToString();
SqlConnection conn = new SqlConnection(GetConnectionString());
TextBox JobAssignedTo = (TextBox)row.FindControl("txtJobAssignedTo");
CheckBox txtCompleted = (CheckBox)row.Cells[1].Controls[0];
TextBox CompletedDate = (TextBox)row.Cells[2].Controls[0];
TextBox Notes = (TextBox)row.Cells[3].Controls[0];
//write your logic here to update the data into the database
conn.Open();
SqlCommand cmd = new SqlCommand("update WO_Submission_Details set Job_Assigned_To='" + JobAssignedTo.Text + "',Completed='" + txtCompleted.Checked + "',Completed_Date='" + CompletedDate.Text + "',Notes='" + Notes.Text + "'where WO_ID='" + WOID + "'", conn);
//SqlCommand cmd = new SqlCommand("update duplicating_request_table set Completed_By=#CompletedBy WHERE Job_No=#JobNo");
cmd.ExecuteNonQuery();
conn.Close();
GridViewAdmin.EditIndex = -1;
//those rows which are deleted previously while updating store it's indexs
if (ViewState["delRows"] == null)
{
int[] delIndices = new int[12];
delIndices[0] = e.RowIndex;
ViewState["delRows"] = delIndices;
}
else
{
int[] delIndices = (int[])ViewState["delRows"];
int itemsLength = delIndices.Count(indx => indx != 0);
delIndices[itemsLength] = e.RowIndex;
}
}
catch (Exception exc)
{
Console.WriteLine(exc);
}
}
}
}
It looks like your SqlDataSource2 is causing the error. Please double check that both Name and Email are of DB type string in your DB.
In your ASPX SqlDataSource2 make the following changes:
<InsertParameters>
<asp:QueryStringParameter Name="Name" QueryStringField="Name" DbType=String />
<asp:QueryStringParameter Name="Email" QueryStringField="Email" DbType=String />
</InsertParameters>
In your C# Code-Behind, change to this:
SqlDataSource2.InsertParameters[0].DefaultValue = txtAddName.Text;

Asp.net GridView RowUpdating returning old values

I am trying to make an editable GridView, and when RowUpdating is called the values I get from the TextBoxes are the old values and not the new ones.
My GridView:
<asp:GridView ID="GVProducts" runat="server" AutoGenerateColumns="False"
CellPadding="4" BackColor="White" BorderColor="#3366CC" BorderStyle="None"
BorderWidth="1px" DataKeyNames="phoneId"
onrowcancelingedit="GVProducts_RowCancelingEdit"
onrowdeleting="GVProducts_RowDeleting"
onrowediting="GVProducts_RowEditing" onrowupdating="GVProducts_RowUpdating"
>
<Columns>
<asp:CommandField ButtonType="Button" EditText="ערוך" HeaderText="עריכה"
InsertText="הוסף" NewText="חדש" SelectText="בחר" ShowEditButton="True"
UpdateText="עדכן" CancelText="בטל" DeleteText="מחק"
InsertVisible="False" CausesValidation="False" />
<asp:CommandField ButtonType="Button" CancelText="בטל" DeleteText="מחק"
EditText="ערוך" InsertText="הוסף" NewText="חדש" SelectText="בחר"
ShowDeleteButton="True" UpdateText="עדכן" HeaderText="מחיקה"
CausesValidation="False" />
<asp:BoundField DataField="phoneId" HeaderText="מספר מכשיר" ReadOnly="True"
SortExpression="phoneId" />
<asp:TemplateField HeaderText="צבע">
<ControlStyle Width="100px" />
<FooterStyle Width="100px" />
<HeaderStyle Width="100px" />
</asp:TemplateField>
<asp:TemplateField HeaderText="חברה">
<ItemTemplate>
<asp:Label ID="lblBrand" runat="server"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="דגם">
<ItemTemplate>
<asp:Label ID="lblModel" runat="server"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="כמות" SortExpression="amount">
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Bind("amount") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("amount") %>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="כמות מינימלית" SortExpression="minAmount">
<ItemTemplate>
<asp:Label ID="Label2" runat="server" Text='<%# Bind("minAmount") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="TextBox2" runat="server" Text='<%# Bind("minAmount") %>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="price" HeaderText="מחיר" SortExpression="price" />
<asp:TemplateField HeaderText="תמונה">
<ItemTemplate>
<asp:Image ID="img" runat="server"
ImageUrl='<%# DataBinder.Eval(Container.DataItem,"pic","images/{0}") %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
<FooterStyle BackColor="#99CCCC" ForeColor="#003399" />
<HeaderStyle BackColor="#003399" Font-Bold="True" ForeColor="#CCCCFF" />
<PagerStyle BackColor="#99CCCC" ForeColor="#003399" HorizontalAlign="Left" />
<RowStyle BackColor="White" ForeColor="#003399" />
<SelectedRowStyle BackColor="#009999" Font-Bold="True" ForeColor="#CCFF99" />
<SortedAscendingCellStyle BackColor="#EDF6F6" />
<SortedAscendingHeaderStyle BackColor="#0D4AC4" />
<SortedDescendingCellStyle BackColor="#D6DFDF" />
<SortedDescendingHeaderStyle BackColor="#002876" />
</asp:GridView>
My RowEditing (UpdateGVLabel is not related):
protected void GVProducts_RowEditing(object sender, GridViewEditEventArgs e)
{
GVProducts.EditIndex = e.NewEditIndex;
GVProducts.DataSource = products;
UpdateGVlabel();
//products = connection.GetData("Select * From Products", "Products");
if (products.Rows.Count > 0)
{
((TextBox)GVProducts.Rows[e.NewEditIndex].Cells[6].Controls[1]).Text = products.Rows[e.NewEditIndex][4].ToString();
((TextBox)GVProducts.Rows[e.NewEditIndex].Cells[7].Controls[1]).Text = products.Rows[e.NewEditIndex][5].ToString();
}
}
My RowUpdating (UpdateGVLabel is not related):
protected void GVProducts_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
bool abort = false;
int amount = 0, minAmount = 0;
int id = int.Parse(GVProducts.Rows[e.RowIndex].Cells[2].Text);
try
{
amount = int.Parse(((TextBox)GVProducts.Rows[e.RowIndex].Cells[6].Controls[1]).Text);
minAmount = int.Parse(((TextBox)GVProducts.Rows[e.RowIndex].Cells[7].Controls[1]).Text);
if (amount < minAmount)
{
MessageBox.Show("אין אפשרות להגדיר כמות שקטנה מהכמות המינימלית!");
abort = true;
}
if (minAmount <= 0)
{
MessageBox.Show("כמות מינימלית לא יכולה להיות אפס או פחות!\nאם ברצונך לציין שהחנות לא מוכרת את המכשיר הזה, יש ללחוץ על \"מחק\"");
abort = true;
}
if (amount < 0)
{
MessageBox.Show("כמות לא יכולה להיות שלילית");
abort = true;
}
}
catch (FormatException)
{
MessageBox.Show("כמויות חייבות להיות מספרים!");
abort = true;
}
if (!abort)
{
connection = new Connect(Server.MapPath("App_Data/ado1.mdb"));
OleDbCommand cmd = new OleDbCommand();
cmd.CommandText = "Update Products Set amount=" + amount + ", minAmount=" + minAmount + " Where phoneId=" + id;
products = connection.GetData("Select * From Products", "Products");
connection.ChangeDatabase(cmd); GVProducts.EditIndex = -1;
GVProducts.DataSource = products;
UpdateGVlabel();
MessageBox.Show("המכשיר נערך בהצלחה!");
}
}
Thanks!
Try this
protected void GVProducts_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
//your code
if (!abort)
{
connection = new Connect(Server.MapPath("App_Data/ado1.mdb"));
OleDbCommand cmd = new OleDbCommand();
cmd.CommandText = "Update Products Set amount=" + amount + ", minAmount=" + minAmount + " Where phoneId=" + id;
cmd.ExecuteNonQuery();//OR "connection.ChangeDatabase(cmd);" if it updates your database
products = connection.GetData("Select * From Products", "Products");
GVProducts.EditIndex = -1;
GVProducts.DataSource = products;
GVProducts.DataBind();
UpdateGVlabel();
MessageBox.Show("המכשיר נערך בהצלחה!");
}
}
The problem was you were calling connection.ChangeDatabase(cmd); to update your database after fetching data from table like this products = connection.GetData("Select * From Products", "Products"); hence you always got old values from your db and values in your db also got updated too..
Also add this GVProducts.DataBind(); after providing datasource GVProducts.DataSource = products; to bind the grid.
Write The code in the row updating
int i=convert.toint32(e.NewValues["Standard"])
IsPostBack() is the answer. We have to check if the Page is posted back or not. If not, then we will bind the Grid.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindGrid();
}
}
Reference : https://taditdash.wordpress.com/2014/06/30/why-gridview-rowupdating-event-is-not-giving-the-updated-values/

Categories

Resources