expected parameter not supplied - c#

I am having some issues using a stored procedure in an asp.net webpage
I have created a stored procedure to insert/update and declare product discontinued.
I am getting the following error:
expected parameter no supplied.
I am not sure why. Any help would be amazing as I am really struggling to get my head around the problem
My markup is as follows:
<asp:Label ID="lblProdGrd" runat="server"></asp:Label>
<asp:GridView
ID="grdProds"
runat="server"
AllowPaging="true"
ShowFooter="true"
PageSize="5"
AutoGenerateColumns="false"
OnPageIndexChanging="grdProds_PageIndexChanging"
OnRowCancelingEdit="grdProds_RowCancelingEdit"
OnRowCommand="grdProds_RowCommand"
OnRowEditing="grdProds_RowEditing"
OnRowUpdating="grdProds_RowUpdating">
<AlternatingRowStyle BackColor="White" ForeColor="#284775" />
<Columns>
<asp:TemplateField AccessibleHeaderText="Product ID" FooterText="Product ID" HeaderText="Product ID">
<ItemTemplate>
<asp:Label ID="lblProdId" Text='<%# Eval("ProductId") %>' runat="server"></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:Label ID="lblAdd" runat="server"></asp:Label>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField AccessibleHeaderText="Product Name" HeaderText="Product Name" FooterText="ProductName">
<ItemTemplate>
<asp:Label ID="lblname" runat="server" Text='<%# Eval("ProductName") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtName" runat="server" Text='<%# Eval("ProductName") %>'></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtAddName" runat="server"></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Product Description" AccessibleHeaderText="Product description" FooterText="Product Description">
<ItemTemplate>
<asp:Label ID="lblDescription" runat="server" Text='<%# Eval("Description")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtDescription" runat="server" Text='<%# Eval("Description")%>' TextMode="MultiLine"></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtAddDescription" runat="server" TextMode="MultiLine"></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Product Price" AccessibleHeaderText="Product Price" FooterText="Product Price">
<ItemTemplate>
<asp:Label ID="lblPrice" runat="server" Text='<%# Eval("Price") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtPrice" runat="server" Text='<%# Eval("Price") %>'></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtAddPrice" runat="server"></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="lblCat" runat="server" Text='<%# Eval("CategoryName") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList ID="lstCatEdit" runat="server">
</asp:DropDownList>
</EditItemTemplate>
<FooterTemplate>
<asp:DropDownList ID="lstCat" runat="server" AppendDataBoundItems="True"
DataTextField='<%# Eval("CategoryName") %>' DataValueField='<%# Eval("CategoryId")%>'>
<asp:ListItem Text="--(Select a category)--" Value="NULL"></asp:ListItem>
</asp:DropDownList>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Sub-Category" AccessibleHeaderText="Sub-Category" FooterText="Sub-Category">
<ItemTemplate>
<asp:Label ID="lblSubCat" runat="server" Text='<%# Eval("ProductType") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList ID="lstSubCat" runat="server"></asp:DropDownList>
</EditItemTemplate>
<FooterTemplate>
<asp:DropDownList ID="lstAddSubCat" runat="server"></asp:DropDownList>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Product Image" AccessibleHeaderText="Product Image" FooterText="Product Image">
<ItemTemplate>
<asp:Image ID="imgProd" runat="server" Height="250" Width="250" ImageUrl='<%# Eval("ImagePath") %>' />
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList ID="lstProdImg" runat="server"></asp:DropDownList>
<asp:Image ID="imgProdEdit" runat="server" Height="250" Width="250" />
</EditItemTemplate>
<FooterTemplate>
<asp:DropDownList ID="lstAddProdImg" runat="server"></asp:DropDownList>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Item in stock" AccessibleHeaderText="Item in stock" FooterText="Item in stock">
<ItemTemplate>
<asp:CheckBox ID="chkInStock" runat="server" Checked='<%# Eval("InStock") %>' Enabled="False" />
</ItemTemplate>
<EditItemTemplate>
<asp:CheckBox ID="chkInStockEdit" runat="server" Checked='<%# Eval("InStock") %>' />
</EditItemTemplate>
<FooterTemplate>
<asp:CheckBox ID="chkInStockAdd" runat="server" />
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Pre-Designed" AccessibleHeaderText="Pre-designed" FooterText="Pre-Designed">
<ItemTemplate>
<asp:CheckBox ID="chkPrePrinted" runat="server" Checked='<%# Eval("PrePrinted") %>' Enabled="False" />
</ItemTemplate>
<EditItemTemplate>
<asp:CheckBox ID="chkPrePrintedEdit" runat="server" Checked='<%# Eval("PrePrinted") %>' />
</EditItemTemplate>
<FooterTemplate>
<asp:CheckBox ID="chkAddPrePrinted" runat="server" />
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Edit">
<ItemTemplate>
<asp:LinkButton ID="btnEdit" Text="Edit" runat="server" CommandName="Edit" />
<br />
<span onclick="return confirm('Are you sure you want to declare this product Discontinued?')">
<asp:LinkButton ID="btnDelete" Text="Delete" runat="server" CommandName="Delete" />
</span>
</ItemTemplate>
<EditItemTemplate>
<asp:LinkButton ID="btnUpdate" Text="Update" runat="server" CommandName="Update" />
<br />
<asp:LinkButton ID="btnCancel" Text="Cancel" runat="server" CommandName="Cancel" />
</EditItemTemplate>
<FooterTemplate>
<asp:Button ID="btnAddRecord" runat="server" Text="Add" CommandName="Add"></asp:Button>
</FooterTemplate>
</asp:TemplateField>
</Columns>
<EditRowStyle BackColor="#999999" />
<FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
<RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
<SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
<SortedAscendingCellStyle BackColor="#E9E7E2" />
<SortedAscendingHeaderStyle BackColor="#506C8C" />
<SortedDescendingCellStyle BackColor="#FFFDF8" />
<SortedDescendingHeaderStyle BackColor="#6F8DAE" />
</asp:GridView
My code behind is as follows:
private string connectionString =
WebConfigurationManager.ConnectionStrings["bncConn"].ConnectionString;
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
BindGrid();
}
}
protected void BindGrid()
{
SqlConnection con = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand("ProductDetails.bnc_Products", con);
cmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
cmd.Parameters.Add(new SqlParameter("#status", SqlDbType.VarChar, 50));
cmd.Parameters["#status"].Value = "Display";
try
{
con.Open();
DataSet ds = new DataSet();
adapter.Fill(ds, "Products");
grdProds.DataSource = ds;
grdProds.DataBind();
}
catch (Exception err)
{
lblProdGrd.Text += err.Message;
}
finally
{
con.Close();
}
}
protected void grdProds_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
grdProds.PageIndex = e.NewPageIndex;
BindGrid();
}
protected void grdProds_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
grdProds.EditIndex = -1;
BindGrid();
}
protected void grdProds_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName.Equals("Add"))
{
TextBox txtName = (TextBox)grdProds.FooterRow.FindControl("txtAddname");
TextBox txtDescription = (TextBox)grdProds.FooterRow.FindControl("txtAddDescription");
TextBox txtPrice = (TextBox)grdProds.FooterRow.FindControl("txtAddPrice");
DropDownList lstCatEdit = (DropDownList)grdProds.FooterRow.FindControl("lstCat");
DropDownList lstSubCat = (DropDownList)grdProds.FooterRow.FindControl("lstAddSubCat");
DropDownList lstImageProd = (DropDownList)grdProds.FooterRow.FindControl("lstAddProdImg");
CheckBox chkInStockEdit = (CheckBox)grdProds.FooterRow.FindControl("chkInStockAdd");
CheckBox chkPrePrinted = (CheckBox)grdProds.FooterRow.FindControl("chkAddPrePinted");
string ProductName, Description, Price, Category, SubCat, Image;
bool InStock, Preprinted;
ProductName = txtName.Text;
Description = txtDescription.Text;
Price = txtPrice.Text;
Category = lstCatEdit.SelectedValue;
SubCat = lstSubCat.SelectedValue;
Image = lstImageProd.SelectedValue;
InStock = chkInStockEdit.Checked;
Preprinted = chkPrePrinted.Checked;
AddProduct(ProductName, Description, Price, Category, SubCat, Image, InStock, Preprinted);
grdProds.EditIndex = -1;
BindGrid();
}
}
protected void AddProduct(string ProductName, string Description, string Price, string Category, string SubCat,
string Image, bool InStock, bool Preprinted)
{
SqlConnection con = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand("ProductDetails.bnc_Products", con);
cmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
cmd.Parameters.Add(new SqlParameter("#Status", "Add"));
cmd.Parameters["#status"].Value = "";
cmd.Parameters.Add(new SqlParameter("#ProductName", SqlDbType.VarChar, 50));
cmd.Parameters["#ProductName"].Value = ProductName;
cmd.Parameters.Add(new SqlParameter("#Description", Description));
cmd.Parameters["#Description"].Value = Description;
cmd.Parameters.Add(new SqlParameter("#Price", SqlDbType.Money));
cmd.Parameters["#Price"].Value = Price;
cmd.Parameters.Add(new SqlParameter("#Category", SqlDbType.Int));
cmd.Parameters["#Category"].Value = Category;
cmd.Parameters.Add(new SqlParameter("#ProductType", SqlDbType.TinyInt));
cmd.Parameters["#ProductType"].Value = SubCat;
cmd.Parameters.Add(new SqlParameter("#Image", SqlDbType.Int));
cmd.Parameters["#Image"].Value = Image;
cmd.Parameters.Add(new SqlParameter("#InStock", SqlDbType.Bit));
cmd.Parameters["#InStock"].Value = InStock;
cmd.Parameters.Add(new SqlParameter("#PrePrinted", SqlDbType.Bit));
cmd.Parameters["#PrePrinted"].Value = Preprinted;
try {
con.Open();
DataSet ds = new DataSet();
adapter.Fill(ds);
}
catch (Exception err)
{
lblProdGrd.Text += err.Message;
}
finally
{
con.Close();
}
}
protected void grdProds_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
Label prId = (Label)grdProds.Rows[e.RowIndex].FindControl("lblProdId");
string pId = prId.Text;
DeleteProduct(pId);
grdProds.EditIndex = -1;
BindGrid();
}
protected void DeleteProduct(string pId)
{
SqlConnection con = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand("ProductDetails.bnc_Products", con);
cmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
cmd.Parameters.Add(new SqlParameter("#Status", SqlDbType.VarChar, 50));
cmd.Parameters["#status"].Value = "Delete";
cmd.Parameters.Add(new SqlParameter("#ProdId", SqlDbType.Int));
cmd.Parameters["#ProdId"].Value = pId;
try
{
con.Open();
DataSet ds = new DataSet();
adapter.Fill(ds);
}
catch (Exception err)
{
lblProdGrd.Text += err.Message;
}
finally
{
con.Close();
}
}
protected void grdProds_RowEditing(object sender, GridViewEditEventArgs e)
{
grdProds.EditIndex = e.NewEditIndex;
BindGrid();
}
protected void grdProds_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
Label prdId = (Label)grdProds.Rows[e.RowIndex].FindControl("lblProdId");
TextBox Name = (TextBox)grdProds.Rows[e.RowIndex].FindControl("txtName");
TextBox Description = (TextBox)grdProds.Rows[e.RowIndex].FindControl("txtDescription");
TextBox Price = (TextBox)grdProds.Rows[e.RowIndex].FindControl("txtPrice");
DropDownList Category = (DropDownList)grdProds.Rows[e.RowIndex].FindControl("lstCatEdit");
DropDownList SubCat = (DropDownList)grdProds.Rows[e.RowIndex].FindControl("lstSubCat");
DropDownList Image = (DropDownList)grdProds.Rows[e.RowIndex].FindControl("lstProdImg");
CheckBox InStock = (CheckBox)grdProds.Rows[e.RowIndex].FindControl("chkInStockEdit");
CheckBox PrePrinted = (CheckBox)grdProds.Rows[e.RowIndex].FindControl("chkPrePrintedEdit");
string ProdId = prdId.Text;
string eName = Name.Text;
string eDescription = Description.Text;
string ePrice = Price.Text;
string eCat = Category.SelectedValue;
string eSCat = SubCat.SelectedValue;
string eImage = Image.SelectedValue;
bool eInstock = InStock.Checked;
bool ePreprinted = PrePrinted.Checked;
UpdateProduct(ProdId, eName, eDescription, ePrice, eCat, eSCat, eImage, eInstock, ePreprinted);
grdProds.EditIndex = -1;
BindGrid();
}
protected void UpdateProduct(string ProdId, string eName, string eDescription, string ePrice, string eCat, string eSCat, string eImage, bool eInstock, bool ePreprinted)
{
SqlConnection con = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand("ProductDetails.bnc_Products", con);
cmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
cmd.Parameters.Add(new SqlParameter("#ProdId", SqlDbType.Int));
cmd.Parameters["#ProdId"].Value = ProdId;
cmd.Parameters.Add(new SqlParameter("#Status", "Update"));
cmd.Parameters["#Status"].Value = "Update";
cmd.Parameters.Add(new SqlParameter("#Category", SqlDbType.Int));
cmd.Parameters["#Category"].Value = eCat;
cmd.Parameters.Add(new SqlParameter("#ProductType", SqlDbType.TinyInt));
cmd.Parameters["#ProductType"].Value = eSCat;
cmd.Parameters.Add(new SqlParameter("#Image", SqlDbType.Int));
cmd.Parameters["#Image"].Value = eImage;
cmd.Parameters.Add(new SqlParameter("#InStock", SqlDbType.Bit));
cmd.Parameters["#InStock"].Value = eInstock;
cmd.Parameters.Add(new SqlParameter("#PrePrinted", SqlDbType.Bit));
cmd.Parameters["#PrePrinted"].Value = ePreprinted;
try
{
con.Open();
DataSet ds = new DataSet();
adapter.Fill(ds);
}
catch (Exception err)
{
lblProdGrd.Text += err.Message;
}
finally
{
con.Close();
}
}
My stored procedure:
CREATE PROCEDURE [ProductDetails].[bnc_Products]
-- Add the parameters for the stored procedure here
#ProdId int,
#Category int,
#ProductType tinyint,
#Price money,
#InStock bit = 1,
#ProductName varchar(50),
#Image int,
#Description varchar(max),
#PrePrinted bit = 1,
#Discontinued bit = 0,
#Status varchar(50)
AS
BEGIN
SET NOCOUNT ON;
if (#Status = 'Display')
begin
select p.ProductId,p.ProductName,c.CategoryId,c.CategoryName,
pt.ProductType,pt.ProductTypeId,p.Price,p.InStock,pi.ImagePath,
pi.ImageId,pi.ImageName,p.Description,p.PrePrinted,p.Discontinued
from ProductDetails.Products p
join ProductDetails.Category c on c.CategoryId = p.Category
join ProductDetails.ProductType pt on pt.ProductTypeId = p.ProductType
join ProductDetails.ProductImages pi on pi.ImageId = p.ImageId
where p.Discontinued = 0
end
else if(#Status = 'Update')
begin
update Productdetails.Products
set Category = #Category, ProductType = #ProductType,
Price = #Price, InStock = #InStock, ProductName = #ProductName,
ImageId = #Image, Description = #Description, PrePrinted = #PrePrinted
where ProductId = #ProdId
end
else if(#Status = 'Add')
begin
insert into ProductDetails.Products (Category,ProductType,Price,InStock,ProductName,ImageId,Description,PrePrinted,Discontinued)
values (#Category,#ProductType,#Price,#InStock,#ProductName,#Image,#Description,#PrePrinted,#Discontinued)
end
else if(#Status = 'Delete')
begin
Update ProductDetails.Products
set Discontinued = #Discontinued
where ProductId = #ProdId
end
END
Any help anyone is able to offer me to resolve this would be wonderful as I have been scratching my head for a few days over this and am no closer to resolving the issue. I apologise if I have not provided all the information you may need, please do not hesitate to ask and I will provide.

I think you try to pass only #Status. Am I right? if yes, then in stored procedure, you need to define parameter with default null value which means you may be pass or not the null parameter and .net not give this error.
#ProdId int = null,
#Category int= null,
#ProductType tinyint = null,
#Price money = null,
#InStock bit = 1, --for this you already mention what is default value. so no need to change. Same thing for below.
#ProductName varchar(50) = null,
#Image int = null,
#Description varchar(max) = null,
#PrePrinted bit = 1,
#Discontinued bit = 0,
#Status varchar(50) = null

Related

How do I maintain editing a row without scrolling back up when I click on the edit button?

I am working in a ASP.NET project in an empty web application in C# and I have made a gridview with CRUD operations. But when I execute my project and click on the buttons I have made it takes me to the first row and I then have to scroll back down again. It is really annoying but I do not know why it does that. Even though I have used MaintainScrollPositionOnPostBack="true" it does not work. Is there anything I cad add to my code or something I have to be aware of?
Default.aspx
<%# Page Language="C#" MaintainScrollPositionOnPostBack="true" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="TestUsers.Default" %>
<link href="TestUsers.css" rel="stylesheet" type="text/css" />
<!DOCTYPE html>
<link rel="stylesheet" href="TestUsers.css">
<link rel="shortcut icon" type="image/x-icon" href="~/orbitone.ico" />
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>ESDTESTERS</title>
<%-- <meta http-equiv="refresh" content="20">--%>
</head>
<body>
<form id="form1" runat="server">
<div>
<div style="margin-left: auto; margin-right: auto; text-align: center;">
<br /><br />
<asp:Button ID="Button2" runat="server" OnClick="Button2_Click" Text="Sing Out" />
<br /><br />
<asp:TextBox ID="TextBox1" runat="server" Width="200px"></asp:TextBox>
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Search" Width="100px" />
<br />
</div>
<asp:GridView ID="gvTestUsers" runat="server" AutoGenerateColumns="False" ShowFooter="True" DataKeyNames="tbl_users_key" ShowHeaderWhenEmpty="True" OnRowCommand="gvTestUsers_RowCommand" OnRowEditing="gvTestUsers_RowEditing" OnRowCancelingEdit="gvTestUsers_RowCancelingEdit"
OnRowDeleting="gvTestUsers_RowDeleting" OnRowUpdating="gvTestUsers_RowUpdating" HorizontalAlign="Center" OnPageIndexChanging="gvTestUsers_PageIndexChanged"
BackColor="#CCCCCC" BorderColor="#000000" BorderStyle="Solid" BorderWidth="3px" CellPadding="5" Width="1300px" CellSpacing="2" ForeColor="Black" PageSize="15" AllowPaging="True" >
<%--Theme Properties--%>
<FooterStyle BackColor="#CCCCCC" />
<HeaderStyle BackColor="Black" Font-Bold="True" Font-Size="Large" ForeColor="White" />
<PagerStyle BackColor="#CCCCCC" ForeColor="Black" HorizontalAlign="Left" />
<RowStyle BackColor="White" />
<SelectedRowStyle BackColor="#000099" Font-Bold="True" ForeColor="White" />
<SortedAscendingCellStyle BackColor="#F1F1F1" />
<SortedAscendingHeaderStyle BackColor="#808080" />
<SortedDescendingCellStyle BackColor="#CAC9C9" />
<SortedDescendingHeaderStyle BackColor="#383838" />
<Columns>
<asp:TemplateField HeaderText="tbl_users_key">
<ItemTemplate>
<asp:Label Text='<%# Eval("tbl_users_key") %>' runat="server" />
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtID" Text='<%# Eval("tbl_users_key") %>' runat="server" ReadOnly="true" />
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Name">
<ItemTemplate>
<asp:Label Text='<%# Eval("Name") %>' runat="server" />
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtName" ReadOnly="True" Text='<%# Eval("Name") %>' runat="server" />
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtNamefooter" runat="server" />
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="CostCenter">
<ItemTemplate>
<asp:Label Text='<%# Eval("CostCenter") %>' runat="server" />
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtCostCenter" ReadOnly="True" Text='<%# Eval("CostCenter") %>' runat="server" />
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtCostCenterfooter" runat="server" />
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Employee">
<ItemTemplate>
<asp:Label Text='<%# Eval("Employee") %>' runat="server" />
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtEmployee" ReadOnly="True" Text='<%# Eval("Employee") %>' runat="server" />
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtEmployeefooter" runat="server" />
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="FootPlate">
<ItemTemplate>
<asp:Label Text='<%# Eval("FootPlate") %>' runat="server" />
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtFootPlate" Text='<%# Eval("FootPlate") %>' runat="server" />
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtFootPlatefooter" runat="server" />
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="WirstCord">
<ItemTemplate>
<asp:Label Text='<%# Eval("WirstCord") %>' runat="server" />
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtWirstCord" Text='<%# Eval("WirstCord") %>' runat="server" />
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtWirstCordfooter" runat="server" />
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Excluded">
<ItemTemplate>
<asp:Label Text='<%# Eval("Excluded") %>' runat="server" />
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtExcluded" Text='<%# Eval("Excluded") %>' runat="server" />
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtExcludedfooter" runat="server" />
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Comment">
<ItemTemplate>
<asp:Label Text='<%# Eval("Comment") %>' runat="server" />
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtComment" Text='<%# Eval("Comment") %>' runat="server" />
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtCommentfooter" runat="server" />
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:ImageButton ImageUrl="~/GridImages/edit.png" runat="server" CommandName="Edit" ToolTip="Edit" Width="20px" Height="20px" />
<asp:ImageButton ImageUrl="~/GridImages/delete.png" runat="server" CommandName="Delete" OnClientClick="return confirm('Are you sure you want to delete this record?');" ToolTip="Delete" Width="20px" Height="20px" />
</ItemTemplate>
<EditItemTemplate>
<asp:ImageButton ImageUrl="~/GridImages/save.png" runat="server" CommandName="Update" ToolTip="Update" Width="20px" Height="20px" />
<asp:ImageButton ImageUrl="~/GridImages/cancel.png" runat="server" CommandName="Cancel" ToolTip="Cancel" Width="20px" Height="20px" />
</EditItemTemplate>
<FooterTemplate>
<asp:ImageButton ImageUrl="~/GridImages/add.png" runat="server" CommandName="AddNew" ToolTip="Add New" Width="20px" Height="20px" />
</FooterTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<br />
<div style="margin-left: auto; margin-right: auto; text-align: center;">
<asp:Label ID="lblSuccessMessage" Text="" runat="server" ForeColor="Green" style="text-align:center" Font-Bold="true" Font-Size="x-Large" />
<br />
<asp:Label ID="lblErrorMessage" Text="" runat="server" ForeColor="Red" style="text-align:center" Font-Bold="true" Font-Size="x-Large" />
</div>
</div>
</form>
</body>
</html>
Default.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
using System.Configuration;
namespace TestUsers
{
public partial class Default : System.Web.UI.Page
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConString"].ConnectionString);
string connectionString = ConfigurationManager.ConnectionStrings["ConString"].ConnectionString;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
PopulateGridView();
}
}
void PopulateGridView()
{
DataTable dtbl = new DataTable();
string connectionString = ConfigurationManager.ConnectionStrings["ConString"].ConnectionString;
using (SqlConnection sqlCon = new SqlConnection(connectionString))
{
sqlCon.Open();
SqlDataAdapter sqlDa = new SqlDataAdapter("Select * FROM TBL_USERS", sqlCon);
sqlDa.Fill(dtbl);
}
if (dtbl.Rows.Count > 0)
{
gvTestUsers.DataSource = dtbl;
gvTestUsers.DataBind();
}
else
{
dtbl.Rows.Add(dtbl.NewRow());
gvTestUsers.DataSource = dtbl;
gvTestUsers.DataBind();
gvTestUsers.Rows[0].Cells.Clear();
gvTestUsers.Rows[0].Cells.Add(new TableCell());
gvTestUsers.Rows[0].Cells[0].ColumnSpan = dtbl.Columns.Count;
gvTestUsers.Rows[0].Cells[0].Text = "No Data Found.";
gvTestUsers.Rows[0].Cells[0].HorizontalAlign = HorizontalAlign.Center;
}
}
protected void gvTestUsers_RowCommand(object sender, GridViewCommandEventArgs e)
{
try
{
if (e.CommandName.Equals("AddNew"))
{
int tbl_users_key = 0;
TextBox myTxt;
myTxt = ((TextBox)gvTestUsers.FooterRow.FindControl("txtNamefooter"));
string Name;
Name = myTxt.Text;
string CostCenter;
myTxt = ((TextBox)gvTestUsers.FooterRow.FindControl("txtCostCenterfooter"));
CostCenter = myTxt.Text;
string Employee;
myTxt = ((TextBox)gvTestUsers.FooterRow.FindControl("txtEmployeefooter"));
Employee = myTxt.Text;
Boolean FootPlate;
myTxt = ((TextBox)gvTestUsers.FooterRow.FindControl("txtFootPlatefooter"));
FootPlate = Convert.ToBoolean(myTxt.Text);
Boolean WirstCord;
myTxt = ((TextBox)gvTestUsers.FooterRow.FindControl("txtWirstCordfooter"));
WirstCord = Convert.ToBoolean(myTxt.Text);
Boolean Excluded;
myTxt = ((TextBox)gvTestUsers.FooterRow.FindControl("txtExcludedfooter"));
Excluded = Convert.ToBoolean(myTxt.Text);
string Comment;
myTxt = ((TextBox)gvTestUsers.FooterRow.FindControl("txtCommentfooter"));
Comment = myTxt.Text;
string sMsg;
sMsg = "";
bool btest = fcEditTBL_USERS(tbl_users_key, Name, CostCenter, Employee, FootPlate, WirstCord, Excluded, Comment, ref sMsg,0);
if (btest == false)
{
lblErrorMessage.Text = sMsg;
lblSuccessMessage.Text = " ";
return;
}
PopulateGridView();
lblSuccessMessage.Text = Name + " Was Added To Record.";
}
}
catch (Exception ex)
{
lblSuccessMessage.Text = "";
lblErrorMessage.Text = ex.Message;
}
}
protected void gvTestUsers_RowEditing(object sender, GridViewEditEventArgs e)
{
gvTestUsers.EditIndex = e.NewEditIndex;
PopulateGridView();
}
protected void gvTestUsers_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
gvTestUsers.EditIndex = -1;
PopulateGridView();
}
protected void gvTestUsers_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
try
{
{
gvTestUsers.EditIndex = e.RowIndex;
PopulateGridView();
//Parameters for delete operation
string dltUsers_key = (gvTestUsers.Rows[e.RowIndex].FindControl("txtID") as TextBox).Text.Trim();
string dltName = (gvTestUsers.Rows[e.RowIndex].FindControl("txtName") as TextBox).Text.Trim();
string dltCostCenter = (gvTestUsers.Rows[e.RowIndex].FindControl("txtCostCenter") as TextBox).Text.Trim();
string dltEmployee = (gvTestUsers.Rows[e.RowIndex].FindControl("txtEmployee") as TextBox).Text.Trim();
string dltFootPlate = (gvTestUsers.Rows[e.RowIndex].FindControl("txtFootPlate") as TextBox).Text.Trim();
string dltWirstCord = (gvTestUsers.Rows[e.RowIndex].FindControl("txtWirstCord") as TextBox).Text.Trim();
string dltExcluded = (gvTestUsers.Rows[e.RowIndex].FindControl("txtExcluded") as TextBox).Text.Trim();
string dltComment = (gvTestUsers.Rows[e.RowIndex].FindControl("txtComment") as TextBox).Text.Trim();
string dltsMsg = "";
//Call function for SP_Delete
bool FuncDelete = fcEditTBL_USERS(Convert.ToInt32(dltUsers_key), dltName, dltCostCenter, dltEmployee, Convert.ToBoolean(dltFootPlate), Convert.ToBoolean(dltWirstCord), Convert.ToBoolean(dltExcluded), dltComment,ref dltsMsg,2);
if (FuncDelete == false)
{
lblErrorMessage.Text = dltsMsg;
lblSuccessMessage.Text = " ";
return;
}
PopulateGridView();
lblSuccessMessage.Text = "Selected Record Deleted.";
lblErrorMessage.Text = "";
gvTestUsers.EditIndex = -1;
}
}
catch (Exception ex)
{
lblSuccessMessage.Text = "";
lblErrorMessage.Text = ex.Message;
}
}
public bool fcEditTBL_USERS
(int tbl_users_key, string Name, string CostCenter, string Employee, bool FootPlate, bool WirstCord, bool Excluded, string Comment, ref string sMsg, int iMode)
{
string connectionString = ConfigurationManager.ConnectionStrings["ConString"].ConnectionString;
using (SqlConnection sqlCon = new SqlConnection(connectionString))
try
{
sqlCon.Open();
SqlCommand sqlCmd = new SqlCommand("spEditTBL_USERS", sqlCon);
sqlCmd.CommandType = CommandType.StoredProcedure;
SqlParameter returnParameter = sqlCmd.Parameters.Add(new SqlParameter("#RETURN_VALUE", DbType.Int32));
returnParameter.Direction = ParameterDirection.ReturnValue;
sqlCmd.Parameters.Add("#ID", SqlDbType.Int).Value=tbl_users_key ;
sqlCmd.Parameters.Add("#Name", SqlDbType.VarChar, 255).Value=Name;
sqlCmd.Parameters.Add("#CostCenter", SqlDbType.VarChar, 10).Value=CostCenter;
sqlCmd.Parameters.Add("#Employee", SqlDbType.VarChar, 32).Value=Employee;
sqlCmd.Parameters.Add("#FootPlate", SqlDbType.Bit).Value=FootPlate;
sqlCmd.Parameters.Add("#WirstCord", SqlDbType.Bit).Value=WirstCord;
sqlCmd.Parameters.Add("#Excluded", SqlDbType.Bit).Value=Excluded;
sqlCmd.Parameters.Add("#Comment", SqlDbType.VarChar, 255).Value=Comment;
sqlCmd.Parameters.Add("#MODE", SqlDbType.SmallInt).Value =iMode;
sqlCmd.Parameters.Add("#MSG", SqlDbType.NVarChar, 255).Value=sMsg;
sqlCmd.Parameters["#MSG"].Direction = ParameterDirection.Output;
sqlCmd.ExecuteNonQuery();
sMsg = sqlCmd.Parameters["#MSG"].Value.ToString();
int rtn = (int)sqlCmd.Parameters["#RETURN_VALUE"].Value;
if (rtn != 0)
{
return false;
}
sqlCmd.Dispose();
return true;
}
finally
{
}
}
protected void gvTestUsers_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
try
{
//Parameters Set From Grid
string tmpUsers_key = (gvTestUsers.Rows[e.RowIndex].FindControl("txtID") as TextBox).Text.Trim();
string tmpName = (gvTestUsers.Rows[e.RowIndex].FindControl("txtName") as TextBox).Text.Trim();
string tmpCostCenter = (gvTestUsers.Rows[e.RowIndex].FindControl("txtCostCenter") as TextBox).Text.Trim();
string tmpEmployee = (gvTestUsers.Rows[e.RowIndex].FindControl("txtEmployee") as TextBox).Text.Trim();
string tmpFootPlate = (gvTestUsers.Rows[e.RowIndex].FindControl("txtFootPlate") as TextBox).Text.Trim();
string tmpWirstCord = (gvTestUsers.Rows[e.RowIndex].FindControl("txtWirstCord") as TextBox).Text.Trim();
string tmpExcluded = (gvTestUsers.Rows[e.RowIndex].FindControl("txtExcluded") as TextBox).Text.Trim();
string tmpComment = (gvTestUsers.Rows[e.RowIndex].FindControl("txtComment") as TextBox).Text.Trim();
string tmpsMsg = "";
//Call function for SP_UPDATE
bool FuncResult = fcEditTBL_USERS(Convert.ToInt32(tmpUsers_key), tmpName, tmpCostCenter, tmpEmployee, Convert.ToBoolean(tmpFootPlate), Convert.ToBoolean(tmpWirstCord), Convert.ToBoolean(tmpExcluded), tmpComment,ref tmpsMsg,1);
//Reload Page
PopulateGridView();
lblSuccessMessage.Text = "Selected Record Updated.";
lblErrorMessage.Text = "";
}
catch (Exception ex)
{
lblSuccessMessage.Text = "";
lblErrorMessage.Text = ex.Message;
}
}
protected void gvTestUsers_PageIndexChanged(object sender, GridViewPageEventArgs e)
{
gvTestUsers.PageIndex = e.NewPageIndex;
PopulateGridView();
}
protected void Button1_Click(object sender, EventArgs e)
{
string find = "select * from TBL_USERS where (Name like '%' + #Name + '%') or (employee like '%' + #Employee + '%')";
SqlCommand comm = new SqlCommand (find,con);
comm.Parameters.Add("#Name", SqlDbType.VarChar, 255).Value = TextBox1.Text;
comm.Parameters.Add("#Employee", SqlDbType.VarChar, 32).Value = TextBox1.Text;
con.Open();
comm.ExecuteNonQuery();
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = comm;
DataSet ds = new DataSet();
da.Fill(ds, "Name");
da.Fill(ds, "Employee");
gvTestUsers.DataSource = ds;
gvTestUsers.DataBind();
con.Close();
}
protected void Button2_Click(object sender, EventArgs e)
{
Response.Redirect("LoginForm.aspx");
}
}
}
Thank you for the explanation. Please try setting gridview editindex before populating the gridview (after updating and deleting ) Hope this helps.
Working below code for me.
protected void gvTestUsers_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
try
{
//Parameters Set From Grid
string tmpUsers_key = (gvTestUsers.Rows[e.RowIndex].FindControl("txtID") as TextBox).Text.Trim();
string tmpName = (gvTestUsers.Rows[e.RowIndex].FindControl("txtName") as TextBox).Text.Trim();
string tmpCostCenter = (gvTestUsers.Rows[e.RowIndex].FindControl("txtCostCenter") as TextBox).Text.Trim();
string tmpEmployee = (gvTestUsers.Rows[e.RowIndex].FindControl("txtEmployee") as TextBox).Text.Trim();
string tmpFootPlate = (gvTestUsers.Rows[e.RowIndex].FindControl("txtFootPlate") as TextBox).Text.Trim();
string tmpWirstCord = (gvTestUsers.Rows[e.RowIndex].FindControl("txtWirstCord") as TextBox).Text.Trim();
string tmpExcluded = (gvTestUsers.Rows[e.RowIndex].FindControl("txtExcluded") as TextBox).Text.Trim();
string tmpComment = (gvTestUsers.Rows[e.RowIndex].FindControl("txtComment") as TextBox).Text.Trim();
string tmpsMsg = "";
//Call function for SP_UPDATE
bool FuncResult = fcEditTBL_USERS(Convert.ToInt32(tmpUsers_key), tmpName, tmpCostCenter, tmpEmployee, tmpFootPlate, tmpWirstCord, tmpExcluded, tmpComment, ref tmpsMsg, "Update");
//add this
gvTestUsers.EditIndex = -1;
PopulateGridView();
lblSuccessMessage.Text = "Selected Record Updated.";
lblErrorMessage.Text = "";
}
catch (Exception ex)
{
lblSuccessMessage.Text = "";
lblErrorMessage.Text = ex.Message;
}
}
And the row deleting below,
protected void gvTestUsers_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
try
{
{
gvTestUsers.EditIndex = e.RowIndex;
PopulateGridView();
//Parameters for delete operation
string dltUsers_key = (gvTestUsers.Rows[e.RowIndex].FindControl("txtID") as TextBox).Text.Trim();
string dltName = (gvTestUsers.Rows[e.RowIndex].FindControl("txtName") as TextBox).Text.Trim();
string dltCostCenter = (gvTestUsers.Rows[e.RowIndex].FindControl("txtCostCenter") as TextBox).Text.Trim();
string dltEmployee = (gvTestUsers.Rows[e.RowIndex].FindControl("txtEmployee") as TextBox).Text.Trim();
string dltFootPlate = (gvTestUsers.Rows[e.RowIndex].FindControl("txtFootPlate") as TextBox).Text.Trim();
string dltWirstCord = (gvTestUsers.Rows[e.RowIndex].FindControl("txtWirstCord") as TextBox).Text.Trim();
string dltExcluded = (gvTestUsers.Rows[e.RowIndex].FindControl("txtExcluded") as TextBox).Text.Trim();
string dltComment = (gvTestUsers.Rows[e.RowIndex].FindControl("txtComment") as TextBox).Text.Trim();
string dltsMsg = "";
//Call function for SP_Delete
bool FuncDelete = fcEditTBL_USERS(Convert.ToInt32(dltUsers_key), dltName, dltCostCenter, dltEmployee, dltFootPlate, dltWirstCord,dltExcluded, dltComment, ref dltsMsg, "Delete");
if (FuncDelete == false)
{
lblErrorMessage.Text = dltsMsg;
lblSuccessMessage.Text = " ";
return;
}
gvTestUsers.EditIndex = -1;
PopulateGridView();
lblSuccessMessage.Text = "Selected Record Deleted.";
lblErrorMessage.Text = "";
}
}
catch (Exception ex)
{
lblSuccessMessage.Text = "";
lblErrorMessage.Text = ex.Message;
}
}
I solved it by moving the SearchBox-Event code into my PopulateGridView.
So now the PopulateGridView looks like this:
void PopulateGridView()
{
string find = "select * from TBL_USERS where (Name like '%' + #Name + '%') or (employee like '%' + #Employee + '%')";
SqlCommand comm = new SqlCommand(find, con);
comm.Parameters.Add("#Name", SqlDbType.VarChar, 255).Value = TextBox1.Text;
comm.Parameters.Add("#Employee", SqlDbType.VarChar, 32).Value = TextBox1.Text;
con.Open();
comm.ExecuteNonQuery();
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = comm;
DataSet ds = new DataSet();
da.Fill(ds, "Name");
da.Fill(ds, "Employee");
gvTestUsers.DataSource = ds;
gvTestUsers.DataBind();
con.Close();
}
And the Searchbox-Event:
protected void Button1_Click(object sender, EventArgs e)
{
PopulateGridView();
}
Else it would jump straight to Void PopulateGridView each time I would try to use an EDIT,CREATE or DELETE operation.

Gridview Footer Not an Instance

I'm trying to get an Automatic ID filler for a gridview footer text box, but every time I run I get the "Not Referred Instance of an object" meaning the method isn't finding the Text box, Right?
But I have the same text box in other method and is working correctly, what its wrong?
Below is the code sample of GridView
<asp:GridView ID="GridView1" runat="server" BackColor="#CCCCCC" BorderColor="#999999" BorderStyle="Solid" BorderWidth="3px" CellPadding="4" CellSpacing="2" ForeColor="Black" AutoGenerateColumns="False" ShowFooter="True">
<Columns>
<asp:TemplateField HeaderText="ID UNIDAD">
<EditItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("ID_UNIDAD") %>'></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtAddID" runat="server" ></asp:TextBox>
</FooterTemplate>
<ItemTemplate>
<asp:Label ID="lbl_ID" runat="server" Text='<%# Bind("ID_UNIDAD") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="UNIDAD">
<EditItemTemplate>
<asp:TextBox ID="TextBox2" runat="server" Text='<%# Bind("NOMBRE") %>'></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtNombre" runat="server" ></asp:TextBox>
</FooterTemplate>
<ItemTemplate>
<asp:Label ID="lbl_Nombre" runat="server" Text='<%# Bind("NOMBRE") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="FRACCIONES">
<EditItemTemplate>
<asp:CheckBox ID="TextBox3" runat="server" Checked='<%# Bind("FRACCIONES") %>'></asp:CheckBox>
</EditItemTemplate>
<FooterTemplate>
<asp:CheckBox ID="chkFraccion" runat="server" ></asp:CheckBox>
</FooterTemplate>
<ItemTemplate>
<asp:CheckBox ID="lbl_Fraccion" runat="server" Checked='<%# Bind("FRACCIONES") %>' ></asp:CheckBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="CLAVE SAT">
<EditItemTemplate>
<asp:TextBox ID="TextBox4" runat="server" Text='<%# Bind("CLAVE_SAT") %>'></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtClave" runat="server" ></asp:TextBox>
</FooterTemplate>
<ItemTemplate>
<asp:Label ID="lbl_Clave" runat="server" Text='<%# Bind("CLAVE_SAT") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<FooterTemplate>
<asp:ImageButton ID="Agregar" runat="server" ImageUrl="~/assets/iconos/add.ico" OnClick="Agregar_Click" />
</FooterTemplate>
</asp:TemplateField>
</Columns>
<FooterStyle BackColor="#CCCCCC" />
<HeaderStyle BackColor="Black" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#CCCCCC" ForeColor="Black" HorizontalAlign="Left" />
<RowStyle BackColor="White" />
<SelectedRowStyle BackColor="#000099" Font-Bold="True" ForeColor="White" />
<SortedAscendingCellStyle BackColor="#F1F1F1" />
<SortedAscendingHeaderStyle BackColor="#808080" />
<SortedDescendingCellStyle BackColor="#CAC9C9" />
<SortedDescendingHeaderStyle BackColor="#383838" />
</asp:GridView>
Below is the code sample for binding the grid in 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.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Web.UI.HtmlControls;
using System.Windows.Input;
public partial class Default2 : System.Web.UI.Page
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["Integral Database"].ToString());
string query;
string countid = " ";
SqlConnection connStr = new SqlConnection(ConfigurationManager.ConnectionStrings["Integral Database"].ToString());
string connStrr = ConfigurationManager.ConnectionStrings["Integral Database"].ConnectionString;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
llenagrid();
IncrementoID();
}
public void llenagrid()
{
DataTable table = new DataTable();
using (SqlConnection conn = new SqlConnection(connStrr))
{
string sql = "SELECT id_unidad, nombre, fracciones, clave_sat from unidades";
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
using (SqlDataAdapter ad = new SqlDataAdapter(cmd))
{
ad.Fill(table);
}
}
}
IncrementoID();
GridView1.DataSource = table;
GridView1.DataBind();
}
protected void Agregar_Click(object sender, ImageClickEventArgs e)
{
connStr.Open();
GridViewRow row = GridView1.FooterRow;
TextBox txtNombre = (TextBox)row.FindControl("txtNombre");
string str = "select count(nombre) from unidades where nombre like '"+txtNombre.Text+ "'";
SqlCommand com = new SqlCommand(str,connStr);
int count = Convert.ToInt32(com.ExecuteScalar());
connStr.Close();
if (count > 0)
{
string script = "alert('Este Nombre ya Existe.','AtenciĆ³n');";
ScriptManager.RegisterStartupScript(this, this.GetType(), "testScript", script, true);
}
else
{
connStr.Open();
TextBox txtID = (TextBox)row.FindControl("txtAddID");
CheckBox chkFracc = (CheckBox)row.FindControl("chkFraccion");
TextBox txtClave = (TextBox)row.FindControl("txtClave");
string ID = txtID.Text;
string Nombre = txtNombre.Text;
bool Fracc = chkFracc.Checked;
string clave = txtClave.Text;
string query2 = "Insert into unidades values('" + ID + "','" + Nombre + "','" + Fracc + "','" + clave + "')";
SqlCommand cmd2 = new SqlCommand(query2, connStr);
cmd2.ExecuteNonQuery();
connStr.Close();
llenagrid();
IncrementoID();
}
}
public void IncrementoID()
{
//query = "select Count(id_unidad) from unidades";
//con.Open();
//SqlCommand cmd = new SqlCommand(query, con);
//string cid = cmd.ExecuteScalar().ToString();
//con.Close();
//TextBox ID = (TextBox)GridView1.FooterRow.FindControl("txtAddID");
//ID.Text = countid + (int.Parse(cid) + 1);
//ID.ReadOnly = true;
con.Open();
SqlCommand cmd = new SqlCommand("select MAX (CAST( ID_UNIDAD as INT)) from unidades",con);
SqlDataReader rd = cmd.ExecuteReader();
TextBox txtID = ((TextBox)GridView1.FooterRow.FindControl("txtAddID"));
if (rd.Read())
{
string Value = rd[0].ToString();
if (Value == "")
{
txtID.Text = "1";
}
else
{
txtID.Text = rd[0].ToString();
txtID.Text = (Convert.ToInt64(txtID.Text) + 1).ToString();
}
}
con.Close();
}
}
As you can see, in the insert method it finds the gridview textbox (txtAddID) and when I try to use the same exact syntax in the IncrementoID Method it doesn't work.
Here is the problem in the method llenagrid(), before binding GridView you are trying to access the control that are in Gridview (inside method IncrementoID), So it's giving error as Not Referred Instance of an object means the Object you are trying to access is not yet referenced. Below code sample can help you out:
public void llenagrid()
{
DataTable table = new DataTable();
using (SqlConnection conn = new SqlConnection(connStrr))
{
string sql = "SELECT id_unidad, nombre, fracciones, clave_sat from unidades";
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
using (SqlDataAdapter ad = new SqlDataAdapter(cmd))
{
ad.Fill(table);
}
}
}
//IncrementoID(); // Remove the function call from here
GridView1.DataSource = table;
GridView1.DataBind();
IncrementoID(); // Call the function after GridView got binded.
}

how to CRUD operation in gridview using 3 tier

I am using n tier architecture
Here is my aspx.cs code
using System;
using System.Web.UI;
using BAL;
using System.Web.UI.WebControls;
namespace GridViewThreeTierApplication
{
public partial class index : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
BindGrid();
}
}
protected void BindGrid()
{
var dataSource = new DAL.dal().GetAllCustomers();
if (dataSource != null)
{
GridView1.DataSource = dataSource;
GridView1.DataBind();
}
}
protected void GridView1_DataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
Control control = e.Row.Cells[0].Controls[0];
if (control is LinkButton)
{
int num = Convert.ToInt32(e.Row.RowIndex);
bal.DeleteCustomers(num);
}
}
}
}
}
here is my markup
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="index.aspx.cs" Inherits="GridViewThreeTierApplication.index" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" CellPadding="4" ForeColor="#333333" GridLines="None" ShowFooter="True" OnDataBound="GridView1_DataBound">
<AlternatingRowStyle BackColor="White" />
<Columns>
<asp:TemplateField ShowHeader="False">
<EditItemTemplate>
<asp:Button ID="LinkButton1" runat="server" Text="Update" CommandName="Update" CausesValidation="true" />
<asp:Button ID="LinkButton2" runat="server" Text="Cancel" CausesValidation="false" CommandName="Cancel" />
</EditItemTemplate>
<ItemTemplate>
<asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="False" CommandName="Edit" Text="Edit"></asp:LinkButton>
<asp:LinkButton ID="LinkButton2" runat="server" CausesValidation="False" CommandName="Delete" Text="Delete"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="CustomerID" SortExpression="CustomerID">
<EditItemTemplate>
<asp:TextBox ID="TextBox5" runat="server" Text='<%# Bind("CustomerID") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label5" runat="server" Text='<%# Bind("CustomerID") %>'></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:Button ID="InsertBtn" runat="server" Text="Insert" />
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="FirstName" SortExpression="FirstName">
<EditItemTemplate>
<asp:TextBox ID="TextBox4" runat="server" Text='<%# Bind("FirstName") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label4" runat="server" Text='<%# Bind("FirstName") %>'></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtFname" runat="server"></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="LastName" SortExpression="LastName">
<EditItemTemplate>
<asp:TextBox ID="TextBox3" runat="server" Text='<%# Bind("LastName") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label3" runat="server" Text='<%# Bind("LastName") %>'></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtFiname" runat="server"></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Email" SortExpression="Email">
<EditItemTemplate>
<asp:TextBox ID="TextBox2" runat="server" Text='<%# Bind("Email") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label2" runat="server" Text='<%# Bind("Email") %>'></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtLname" runat="server"></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="PhoneNumber" SortExpression="PhoneNumber">
<EditItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("PhoneNumber") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Bind("PhoneNumber") %>'></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtFirname" runat="server"></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:CommandField />
</Columns>
<FooterStyle BackColor="#990000" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#990000" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#FFCC66" ForeColor="#333333" HorizontalAlign="Center" />
<RowStyle BackColor="#FFFBD6" ForeColor="#333333" />
<SelectedRowStyle BackColor="#FFCC66" Font-Bold="True" ForeColor="Navy" />
<SortedAscendingCellStyle BackColor="#FDF5AC" />
<SortedAscendingHeaderStyle BackColor="#4D0000" />
<SortedDescendingCellStyle BackColor="#FCF6C0" />
<SortedDescendingHeaderStyle BackColor="#820000" />
</asp:GridView>
</div>
</form>
</body>
</html>
here is my data access layer
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Configuration;
namespace DAL
{
public class dal
{
public class Customer
{
public int CustomerID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Email { get; set; }
public int PhoneNumber { get; set; }
}
public List<Customer> GetAllCustomers()
{
List<Customer> listCustomers = new List<Customer>();
string CS = ConfigurationManager.ConnectionStrings["Intial_DatabaseConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(CS))
{
SqlCommand cmd = new SqlCommand("Select * from Customer", con);
con.Open();
SqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
Customer Customer = new Customer();
Customer.CustomerID = Convert.ToInt32(rdr["CustomerID"]);
Customer.FirstName = rdr["FirstName"].ToString();
Customer.LastName = rdr["LastName"].ToString();
Customer.Email = rdr["Email"].ToString();
Customer.PhoneNumber = Convert.ToInt32(rdr["PhoneNumber"]);
listCustomers.Add(Customer);
}
}
return listCustomers;
}
}
}
here is my business object
using System.Configuration;
using System.Data.SqlClient;
namespace BAL
{
public class bal
{
protected void GetALLCustomer()
{
}
public static void DeleteCustomers(int CustomerID)
{
string CS = ConfigurationManager.ConnectionStrings["Intial_DatabaseConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(CS))
{
SqlCommand cmd = new SqlCommand ("Delete from Customer where CustomerID = #CustomerID", con);
SqlParameter param = new SqlParameter("#CustomerId", CustomerID);
cmd.Parameters.Add(param);
con.Open();
cmd.ExecuteNonQuery();
}
}
public static int InsertCustomers(string FirstName, string LastName, string Email, int PhoneNumber)
{
string CS = ConfigurationManager.ConnectionStrings["Intial_DatabaseConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(CS))
{
string updateQuery = "Insert into Customers (FirstName, LastName, Email,PhoneNumber)" +
" values (#FirstName, #LastName, #Email,#PhoneNumber)";
SqlCommand cmd = new SqlCommand(updateQuery, con);
SqlParameter paramFirstName = new SqlParameter("#FirstName", FirstName);
cmd.Parameters.Add(paramFirstName);
SqlParameter paramLastName = new SqlParameter("#LastName", LastName);
cmd.Parameters.Add(paramLastName);
SqlParameter paramEmail = new SqlParameter("#Email", Email);
cmd.Parameters.Add(paramEmail);
SqlParameter paramPhoneNumber = new SqlParameter("#PhoneNumber", PhoneNumber);
con.Open();
return cmd.ExecuteNonQuery();
}
}
}
}
I am able to perform select query .
I can not perform Create ,Delete or Update .
It seems like the phone number parameter is not on the cmd command
Here is how i got it to work
1) First i deleted event GridView1_DataBound
Delete "CommandField" column from GridView1 (markup)
<asp:CommandField ShowDeleteButton="True" ShowEditButton="True" />
2) insert this markup in its place
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="lbEdit" CommandArgument='<%# Eval("EmployeeId") %>' CommandName="EditRow" ForeColor="#8C4510" runat="server">Edit</asp:LinkButton>
<asp:LinkButton ID="lbDelete" CommandArgument='<%# Eval("EmployeeId") %>' CommandName="DeleteRow" ForeColor="#8C4510" runat="server" CausesValidation="false">Delete</asp:LinkButton>
</ItemTemplate>
<EditItemTemplate>
<asp:LinkButton ID="lbUpdate" CommandArgument='<%# Eval("EmployeeId") %>' CommandName="UpdateRow" ForeColor="#8C4510" runat="server">Update</asp:LinkButton>
<asp:LinkButton ID="lbCancel" CommandArgument='<%# Eval("EmployeeId") %>' CommandName="CancelUpdate" ForeColor="#8C4510" runat="server" CausesValidation="false">Cancel</asp:LinkButton>
</EditItemTemplate>
</asp:TemplateField>
3) insert this FooterTemplate of EmployeeId
Insert
4) Now generate GridView1_RowCommand() event handler method.
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "EditRow")
{
int rowIndex = ((GridViewRow)((LinkButton)e.CommandSource).NamingContainer).RowIndex;
GridView1.EditIndex = rowIndex;
BindGrid();
}
else if (e.CommandName == "DeleteRow")
{
BAL.bal.DeleteCustomers(Convert.ToInt32(e.CommandArgument));
BindGrid();
}
else if (e.CommandName == "CancelUpdate")
{
GridView1.EditIndex = -1;
BindGrid();
}
else if (e.CommandName == "UpdateRow")
{
int rowIndex = ((GridViewRow)((LinkButton)e.CommandSource).NamingContainer).RowIndex;
int CustomerId = Convert.ToInt32(e.CommandArgument);
string Name = ((TextBox)GridView1.Rows[rowIndex].FindControl("TextBox1")).Text;
string Gender = ((DropDownList)GridView1.Rows[rowIndex].FindControl("DropDownList1")).SelectedValue;
string City = ((TextBox)GridView1.Rows[rowIndex].FindControl("TextBox3")).Text;
BAL.bal.UpdateCustomers(CustomerId, Name, Gender, City);
GridView1.EditIndex = -1;
BindGrid();
}
else if (e.CommandName == "InsertRow")
{
string Name = ((TextBox)GridView1.FooterRow.FindControl("txtName")).Text;
string Gender = ((DropDownList)GridView1.FooterRow.FindControl("ddlGender")).SelectedValue;
string City = ((TextBox)GridView1.FooterRow.FindControl("txtCity")).Text;
BAL.bal.InsertCustomers(name, gender, city);
BindGrid();
}
}
6) Correct insertCustomer Method
public static int InsertCustomers(string Name, string Gender, string City)
{
string CS = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
using (SqlConnection con = new SqlConnection(CS))
{
string updateQuery = "Insert into tblEmployee (Name, Gender, City)" +
" values (#Name, #Gender, #City)";
SqlCommand cmd = new SqlCommand(updateQuery, con);
SqlParameter paramName = new SqlParameter("#Name", Name);
cmd.Parameters.Add(paramName);
SqlParameter paramGender = new SqlParameter("#Gender", Gender);
cmd.Parameters.Add(paramGender);
SqlParameter paramCity = new SqlParameter("#City", City);
cmd.Parameters.Add(paramCity);
con.Open();
return cmd.ExecuteNonQuery();
}
}
If you want to show a confirmation dialog box, before a row is deleted, include javascript confirm() function, using "OnClientClick" attribute of LinkButton "lbDelete".
<asp:LinkButton ID="lbDelete" CommandArgument='<%# Eval("EmployeeId") %>' CommandName="DeleteRow" ForeColor="#8C4510" runat="server" CausesValidation="false" OnClientClick="return confirm('Are you sure you want to delete this row');">Delete</asp:LinkButton>

dropdownlist name has a SelectedValue which is invalid because it does not exist in the list of items

What I want to achieve is when I click on edit, the Blogtype field in the gridview will be changed to dropdownlist. And Since my database have 3 data in the blogtype which is community work, competition and overseas experience. The dropdownlist will be allows me to select either of these three. After choosing either of this one, and I clicked update, it will be updated in the database. How to do it as I have error in the 3rd screenshot.The name of my dropdownlist for blogtype field is ddlBlogType. help
But for my current code, after clicking edit, it will come out this error. 'ddlBlogType' has a SelectedValue which is invalid because it does not exist in the list of items.
Parameter name: value
Source Code
<asp:GridView ID="grdBlog" runat="server" style=
"margin-left: 0px" Width="1000px" Height="147px" AutoGenerateColumns="False"
onrowcancelingedit="grdBlog_RowCancelingEdit" onrowediting="grdBlog_RowEditing"
onrowupdating="grdBlog_RowUpdating" DataKeyNames="BlogID"
onrowdeleting="grdBlog_RowDeleting" AllowPaging="True"
onpageindexchanging="grdBlog_PageIndexChanging" PageSize="5"
BackColor="White" BorderColor="White" BorderStyle="Ridge" BorderWidth="2px"
CellPadding="3" CellSpacing="1" GridLines="None" >
<Columns>
<asp:BoundField DataField="BlogID" HeaderText="BlogID" ReadOnly="true"
SortExpression="BlogID" />
<asp:TemplateField HeaderText="Name">
<EditItemTemplate>
<asp:TextBox ID="txtName" runat="server" Width="80px" Text='<%# Bind("Name") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Bind("Name") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="BlogType">
<EditItemTemplate>
<asp:DropDownList ID="ddlBlogType" runat="server" Width="80px" Text='<%# Bind("BlogType") %>'></asp:DropDownList>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label2" runat="server" Text='<%# Bind("BlogType") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Description">
<EditItemTemplate>
<asp:TextBox ID="txtDescription" runat="server" Width="80px" Text='<%# Bind("Description") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label3" runat="server" Text='<%# Bind("Description") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="DateEntry" HeaderText="Date Entry" ReadOnly="true" />
<asp:TemplateField HeaderText="Blog Story">
<EditItemTemplate>
<asp:TextBox ID="txtBlogStory" runat="server" TextMode="multiline" rows="10" Text='<%# Bind("BlogStory") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label5" runat="server" Text='<%# Bind("BlogStory") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="modifiedby" HeaderText="Last Modified By" ReadOnly="true" />
<asp:BoundField DataField="modifieddate" HeaderText="Last Modified Date" ReadOnly="true" />
<asp:CommandField ShowEditButton="True" CausesValidation="false" />
<asp:TemplateField ShowHeader="False">
<ItemTemplate>
<asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="False"
CommandName="Delete" Text="Delete" OnClientClick="javascript : return confirm('Confirm delete this record?');"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<FooterStyle BackColor="#C6C3C6" ForeColor="Black" />
<HeaderStyle BackColor="#4A3C8C" Font-Bold="True" ForeColor="#E7E7FF" />
<PagerStyle BackColor="#C6C3C6" ForeColor="Black" HorizontalAlign="Right" />
<RowStyle BackColor="#DEDFDE" ForeColor="Black" />
<SelectedRowStyle BackColor="#9471DE" Font-Bold="True" ForeColor="White" />
<SortedAscendingCellStyle BackColor="#F1F1F1" />
<SortedAscendingHeaderStyle BackColor="#594B9C" />
<SortedDescendingCellStyle BackColor="#CAC9C9" />
<SortedDescendingHeaderStyle BackColor="#33276A" />
</asp:GridView>
Code Behind Code
if (Page.IsPostBack == false)
{
bindResultGridView();
}
private void bindResultGridView()
{
String ConStr = ConfigurationManager.ConnectionStrings["BlogConnectionString"].ConnectionString;
SqlConnection con = new SqlConnection(ConStr);
try
{
String SQL = null;
SQL = "SELECT BlogID, Name, Blogtype, Description, convert(varchar,Dateentry, 103) as Dateentry, BlogStory, modifiedby, convert(varchar,modifieddate, 103) as modifieddate FROM [EntryTable] ORDER BY BlogID DESC";
SqlCommand cmd = new SqlCommand(SQL, con);
con.Open();
SqlDataReader reader = cmd.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(reader);
grdBlog.DataSource = dt;
grdBlog.DataBind();
reader.Close();
}
finally
{
con.Close();
}
}
protected void grdBlog_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
grdBlog.EditIndex = -1;
bindResultGridView();
}
protected void grdBlog_RowEditing(object sender, GridViewEditEventArgs e)
{
grdBlog.EditIndex = e.NewEditIndex;
bindResultGridView();
}
protected void grdBlog_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
int selectedRow = e.RowIndex; //get selected row
// get product id from data key
int blogid = (int)grdBlog.DataKeys[selectedRow].Value;
// get current grid view row
GridViewRow row = (GridViewRow)grdBlog.Rows[selectedRow];
TextBox name = (TextBox)row.FindControl("txtName");
// find text box for txtPrice
DropDownList blogtype = (DropDownList)row.FindControl("ddlBlogType");
TextBox description = (TextBox)row.FindControl("txtDescription");
TextBox blogstory = (TextBox)row.FindControl("txtBlogStory");
// Remove $ sign
string strName = name.Text;
string strBlogType = blogtype.Text;
string strDescription = description.Text;
string strBlogStory = blogstory.Text;
/*
DateTime datDate;
*/
/*
if (DateTime.TryParseExact(strDateEntry, new string[] { "dd/MM/yyyy" },
System.Globalization.CultureInfo.InvariantCulture,
System.Globalization.DateTimeStyles.None, out datDate))
{
*/
updateBlogGridviewRecord(blogid, strName, strBlogType, strDescription, strBlogStory);
/*
}
else
{
lblError.Visible = true;
lblError.Text = "Invalid Date";
lblSuccess.Visible = false;
}
*/
}
private void updateBlogGridviewRecord(int blogid, string strName, string strBlogType, string strDescription, string strBlogStory)
{
try
{
string strConnectionString = ConfigurationManager.ConnectionStrings["BlogConnectionString"].ConnectionString;
SqlConnection myConnect = new SqlConnection(strConnectionString);
string strCommandText = "UPDATE EntryTable SET [ModifiedBy]=#Modifier, [ModifiedDate] = GETDATE(), [Name]=#Name, [BlogType]=#BlogType, [Description]=#Description, [BlogStory]=#BlogStory WHERE [BlogID]=#BlogID";
/*string strCommandText = "UPDATE EntryTable SET [Name]=#Name, [BlogType]=#BlogType, [Description]=#Description, [DateEntry]=#DateEntry, [BlogStory]=#BlogStory WHERE [BlogID]=#BlogID"; */
/*string strCommandText = "UPDATE EntryTable SET [ModifiedBy] = [Name], [Name]=#Name, [BlogType]=#BlogType, [Description]=#Description, [DateEntry]=#DateEntry, [BlogStory]=#BlogStory WHERE [BlogID]=#BlogID"; */
SqlCommand cmd = new SqlCommand(strCommandText, myConnect);
cmd.Parameters.AddWithValue("#BlogID", blogid);
cmd.Parameters.AddWithValue("#Name", strName);
cmd.Parameters.AddWithValue("#BlogType", strBlogType);
//cmd.Parameters.AddWithValue("#DateEntry", datDate);
cmd.Parameters.AddWithValue("#Description", strDescription);
cmd.Parameters.AddWithValue("#BlogStory", strBlogStory);
cmd.Parameters.AddWithValue("#Modifier", Session["Username"]);
myConnect.Open();
int result = cmd.ExecuteNonQuery();
if (result > 0)
{
lblSuccess.Visible = true;
lblSuccess.Text = "Record updated!";
lblError.Visible = false;
}
else
{
lblSuccess.Visible = true;
lblError.Text = "Update fail";
lblError.Visible = false;
}
myConnect.Close();
//Cancel Edit Mode
grdBlog.EditIndex = -1;
bindResultGridView();
}
catch
{
lblError.Visible = true;
lblError.Text = "Invalid Data";
lblSuccess.Visible = false;
}
}
Did it using the edited code below
Source Code
<asp:TemplateField HeaderText="BlogType">
<EditItemTemplate>
<asp:DropDownList ID="ddlBlogType" runat="server" DataTextField="ddlBlogType" DataValueField="ddlBlogType" SelectedValue='<%# Eval("blogType") %>'>
<asp:ListItem Enabled="true" Text="Community Work" Value="Community Work"></asp:ListItem>
<asp:ListItem Text="Competition" Value="Competition"></asp:ListItem>
<asp:ListItem Text="Overseas Experience" Value="Overseas Experience"></asp:ListItem>
</asp:DropDownList>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label2" runat="server" Text='<%# Bind("BlogType") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
Code behind Code
protected void grdBlog_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
int selectedRow = e.RowIndex; //get selected row
// get product id from data key
int blogid = (int)grdBlog.DataKeys[selectedRow].Value;
// get current grid view row
GridViewRow row = (GridViewRow)grdBlog.Rows[selectedRow];
TextBox name = (TextBox)row.FindControl("txtName");
// find text box for txtPrice
DropDownList blogtype = (DropDownList)row.FindControl("ddlBlogType");
TextBox description = (TextBox)row.FindControl("txtDescription");
TextBox blogstory = (TextBox)row.FindControl("txtBlogStory");
// Remove $ sign
string strName = name.Text;
string strBlogType = blogtype.SelectedValue;
string strDescription = description.Text;
string strBlogStory = blogstory.Text;
}
I see the issue as the way you populate the DropDownList. The code isn't shown in your post, so assuming you don't have anything to that effect.
So you normally set the desired gridviewrow in edit mode as below:
protected void grdBlog_RowEditing(object sender, GridViewEditEventArgs e)
{
grdBlog.EditIndex = e.NewEditIndex;
bindResultGridView();
}
Now we need to figure when exactly to bind the dropdownlist. Therefore when the particular datarow (which is in edit mode) is getting databound we have a chance to obtain the reference to the corresponding edit row's dropdownlist. Hence for this you can refer this post.
In summary you need to handle the DataBound event of the gridview and determine from its rowstate what mode it is in. Sharing the code sample from linked post below:
protected void gv_RowDataBound(object sender, GridViewEditEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
if ((e.Row.RowState & DataControlRowState.Edit) > 0)
{
DropDownList ddList= (DropDownList)e.Row.FindControl("DStatusEdit");
//bind dropdownlist
DataTable dt = con.GetData("select distinct status from directory");
ddList.DataSource = dt;
ddList.DataTextField = "YourCOLName";
ddList.DataValueField = "YourCOLName";
ddList.DataBind();
DataRowView dr = e.Row.DataItem as DataRowView;
//ddList.SelectedItem.Text = dr["YourCOLName"].ToString();
ddList.SelectedValue = dr["YourCOLName"].ToString();
}
}
}

Grid Showing old values after updation using ObjectDataSource to bind and Update the grid

I am using ObjectDataSource to Bind and update the grid .It is working fine and the records are updating in the database but after updating ,it is still showing the same records in the grid (Previous Values). Please help me that what i will do so that after database updation, The grid will display updated records ,not the old records.Please modify my code also in case if any one found the solution.
Thanks in Advance.
Please find the code below.
GridView Code:-
<asp:Panel ID="pnlGrdShift" runat="server" ScrollBars="Auto" Width="900px" Height="520px" CssClass="srcColor">
<cc1:GridView ID="gvShift" runat="server" AutoGenerateColumns="False" AllowSorting="True"
CssClass="grid"
OnDataBound="gvShift_DataBound"
DataSourceID="odsShiftDetails"
AllowPaging="True"
ShowFooter="false"
onrowcancelingedit="gvShift_RowCancelingEdit"
onrowcommand="gvShift_RowCommand"
onrowdeleting="gvShift_RowDeleting"
onrowediting="gvShift_RowEditing"
onrowupdating="gvShift_RowUpdating"
OnSelectedIndexChanged="gvShift_SelectedIndexChanged"
OnRowDataBound="gvShift_RowDataBound">
<AlternatingRowStyle CssClass="altrowstyle" />
<HeaderStyle CssClass="headerstyle" />
<RowStyle CssClass="rowstyle" Wrap="false" />
<EmptyDataRowStyle BackColor="#edf5ff" Height="300px" VerticalAlign="Middle" HorizontalAlign="Center" />
<EmptyDataTemplate >
No Records Found
</EmptyDataTemplate>
<Columns>
<asp:TemplateField HeaderText="E Code" SortExpression="userecode" HeaderStyle-Font-Bold="true" HeaderStyle-Font-Names="Calibre" HeaderStyle-ForeColor="White">
<ItemTemplate>
<asp:Label ID="lblUserECode" runat="server" Text='<%#Eval("userecode") %>' CssClass="GridContent" />
</ItemTemplate>
<EditItemTemplate>
<asp:Label ID="lblEditUserECode" runat="server" Text='<%#Eval("userecode") %>' style="width:50px;" CssClass="GridContent" />
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="User Name" SortExpression="username" HeaderStyle-Font-Bold="true" HeaderStyle-Font-Names="Calibre" HeaderStyle-ForeColor="White">
<ItemTemplate>
<asp:Label ID="lblUserName" runat="server" Text='<%#Eval("username") %>' CssClass="GridContent" />
</ItemTemplate>
<EditItemTemplate>
<asp:Label ID="lblEditUserName" runat="server" Text='<%#Eval("username") %>' style="width:100px;" CssClass="GridContent"/>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Shift Start Time" SortExpression="ShiftStartTime" HeaderStyle-Font-Bold="true" HeaderStyle-Font-Names="Calibre" HeaderStyle-ForeColor="White">
<ItemTemplate>
<asp:Label ID="lblShiftStartTime" runat="server" Text='<%#Eval("ShiftStartTime") %>' CssClass="GridContent"/>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="ddlShiftStartTime" runat="server" Text='<%#Eval("ShiftStartTime") %>' style="width:65px;" CssClass="GridContent" />
<asp:RegularExpressionValidator ID="RegularExpValidatorddlShiftStartTime" runat="server" ControlToValidate="ddlShiftStartTime" ValidationExpression="^([0-9]|0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]$" ErrorMessage="*" Font-Bold="true" ForeColor="Red" ToolTip="Must be in HH:MM" />
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Shift End Time" SortExpression="ShiftEndTime" HeaderStyle-Font-Bold="true" HeaderStyle-Font-Names="Calibre" HeaderStyle-ForeColor="White">
<ItemTemplate>
<asp:Label ID="lblShiftEndTime" runat="server" Text='<%#Eval("ShiftEndTime") %>' CssClass="GridContent" />
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="ddlShiftEndTime" runat="server" Text='<%#Eval("ShiftEndTime") %>' style="width:65px;" CssClass="GridContent" />
<asp:RegularExpressionValidator ID="RegularExpValidatorddlShiftEndTime" runat="server" ControlToValidate="ddlShiftEndTime" ValidationExpression="^([0-9]|0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]$" ErrorMessage="*" Font-Bold="true" ForeColor="Red" ToolTip="Must be in HH:MM" />
</EditItemTemplate>
</asp:TemplateField>
<%--<asp:BoundField DataField="ShiftEndTIme" HeaderText="Shift End Time" SortExpression="ShiftEndTIme"/>--%>
<asp:TemplateField HeaderText="Saturday Shift Start Time" SortExpression="WeekendShiftStartTime" HeaderStyle-Font-Bold="true" HeaderStyle-Font-Names="Calibre" HeaderStyle-ForeColor="White">
<ItemTemplate>
<asp:Label ID="lblWeekendShiftStartTime" runat="server" Text='<%#Eval("WeekendShiftStartTime") %>' CssClass="GridContent" />
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="ddlWeekendShiftStartTime" runat="server" Text='<%#Eval("WeekendShiftStartTime") %>' style="width:65px;" CssClass="GridContent" />
<asp:RegularExpressionValidator ID="RegularExpValidatorddlWeekendShiftStartTime" runat="server" ControlToValidate="ddlWeekendShiftStartTime" ValidationExpression="^([0-9]|0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]$" ErrorMessage="*" Font-Bold="true" ForeColor="Red" ToolTip="Must be in HH:MM" />
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Saturday Shift End Time" SortExpression="weekendshiftendtime" HeaderStyle-Font-Bold="true" HeaderStyle-Font-Names="Calibre" HeaderStyle-ForeColor="White">
<ItemTemplate>
<asp:Label ID="lblWeekendShiftEndTime" runat="server" Text='<%#Eval("weekendshiftendtime") %>' CssClass="GridContent"/>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="ddlWeekendShiftEndTime" runat="server" Text='<%#Eval("weekendshiftendtime") %>' style="width:65px;" CssClass="GridContent" />
<asp:RegularExpressionValidator ID="RegularExpValidatorddlWeekendShiftEndTime" runat="server" ControlToValidate="ddlWeekendShiftEndTime" ValidationExpression="^([0-9]|0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]$" ErrorMessage="*" Font-Bold="true" ForeColor="Red" ToolTip="Must be in HH:MM" />
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField ShowHeader="False" >
<EditItemTemplate>
<asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="True" CommandName="Update" Text="Update" ForeColor="White"></asp:LinkButton>
<asp:LinkButton ID="LinkButton2" runat="server" CausesValidation="False" CommandName="Cancel" Text="Cancel" ForeColor="White"></asp:LinkButton>
</EditItemTemplate>
<ItemTemplate>
<asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="False" CommandName="Edit" Text="Edit" ForeColor="White"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<PagerTemplate >
<table width="100%" >
<tr>
<td style="text-align: left">
Page Size:
<asp:DropDownList ID="ddPageSize" runat="server" EnableViewState="true" OnSelectedIndexChanged="ddPageSize_SelectedIndexChanged" AutoPostBack="true" style="width:50px;">
<asp:ListItem Text="10" ></asp:ListItem>
<asp:ListItem Text="20" ></asp:ListItem>
<asp:ListItem Text="30" ></asp:ListItem>
<asp:ListItem Text="40" ></asp:ListItem>
<asp:ListItem Text="50" ></asp:ListItem>
</asp:DropDownList>
</td>
<td style="text-align: right">
<asp:Label ID="lblPageCount" runat="server"></asp:Label>
</td>
</tr>
</table>
</PagerTemplate>
</cc1:GridView>
</asp:Panel>
<asp:ObjectDataSource ID="odsShiftDetails" runat="server"
SelectMethod="GetShiftInfoSortedPage" TypeName="EQ.DAL.ShiftInfoDB"
EnablePaging="True" SelectCountMethod="GetShiftInfoCount"
SortParameterName="sortExpression" UpdateMethod="UpdateShift">
<UpdateParameters>
<asp:Parameter Name="sql"/>
</UpdateParameters>
<SelectParameters>
<asp:ControlParameter ControlID="hfSearchCriteria" Name="searchCriteria" Direction="Input" />
</SelectParameters>
</asp:ObjectDataSource>
Code Behind for Update:-
protected void gvShift_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
try
{
TextBox txtShiftStartTime = (TextBox)gvShift.Rows[e.RowIndex].FindControl("ddlShiftStartTime");
TextBox txtShiftEndTime = (TextBox)gvShift.Rows[e.RowIndex].FindControl("ddlShiftEndTime");
TextBox txtWeekendShiftStartTime = (TextBox)gvShift.Rows[e.RowIndex].FindControl("ddlWeekendShiftStartTime");
TextBox txtWeekendShiftEndTime = (TextBox)gvShift.Rows[e.RowIndex].FindControl("ddlWeekendShiftEndTime");
Label lblUserecode = (Label)gvShift.Rows[e.RowIndex].FindControl("lblEditUserECode");
string userecode = lblUserecode.Text.ToString();
string _ShiftStart = txtShiftStartTime.Text.ToString();
string _ShiftEnd = txtShiftEndTime.Text.ToString();
string _WeekendShiftStart = txtWeekendShiftStartTime.Text.ToString();
string _WeekendShiftend = txtWeekendShiftEndTime.Text.ToString();
EmployeeQuotientCL.Entities.ConfigurationVariables _configVariables = new ConfigurationVariables();
string databaseConnectionString = _configVariables.ConnectionString;
SqlConnection sqlConnection = null;
if (((databaseConnectionString + string.Empty) != string.Empty))
{
DBConnect dbConnect = new DBConnect(_configVariables.ConnectionString);
sqlConnection = dbConnect.SQLConnection;
SqlCommand cmd = new SqlCommand();
cmd.Connection = sqlConnection;
string sql=null;
cmd.CommandText = "UPDATE UserInfo SET ShiftStartTime ='" + _ShiftStart + "',ShiftEndTime='" + _ShiftEnd.ToString() + "',Weekendshiftstarttime='" + _WeekendShiftStart.ToString() + "',Weekendshiftendtime='" + _WeekendShiftend.ToString() + "' WHERE UserECode=" + userecode.ToString();
odsShiftDetails.UpdateParameters["sql"].DefaultValue = cmd.CommandText;
odsShiftDetails.Update();
}
}
catch (Exception ex)
{
}
}
ShiftInfoDBCache.cs
public class ShiftInfoDB
{
private const string SHIFTINFO_CACHE_KEY = "SHIFTINFO_DATA";
private const string SHIFTINFOCOUNT_CACHE_KEY = "SHIFTINFO_COUNT";
static EmployeeQuotientCL.Entities.ConfigurationVariables _config = new EmployeeQuotientCL.Entities.ConfigurationVariables();
static int _SupervisorecodeforShift;
public static DataTable GetShiftInfoSortedPage(int maximumRows, int startRowIndex, string sortExpression, string searchCriteria)
{
_SupervisorecodeforShift=EmployeeQuotientCL.Entities.StaticGlobalValue.UserId;
if (string.IsNullOrEmpty(sortExpression))
sortExpression = "userecode";
try
{
if (ShiftInfoDBCache.isRecordsCached(SHIFTINFO_CACHE_KEY))
return ShiftInfoDBCache.GetData(SHIFTINFO_CACHE_KEY, startRowIndex + 1, maximumRows, sortExpression, searchCriteria);
SqlConnection dbConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["DBConnectionString"].ToString());
string sql = "select distinct MP.userecode,UI.username,UI.ShiftStartTime,UI.ShiftEndTime,UI.WeekendShiftStartTime,UI.weekendshiftendtime from AssociateSupervisorMapping MP inner join UserInfo UI on MP.Userecode=UI.Userecode where supervisorecode=" + _SupervisorecodeforShift.ToString();
SqlCommand custCommand = new SqlCommand(sql, dbConnection);
custCommand.CommandType = CommandType.Text;
SqlDataAdapter ad = new SqlDataAdapter(custCommand);
DataTable dtCustomers = new DataTable();
ad.Fill(dtCustomers);
dbConnection.Close();
//Cache records
ShiftInfoDBCache.Add(SHIFTINFO_CACHE_KEY, dtCustomers);
}
catch (Exception e)
{
throw;
}
return ShiftInfoDBCache.GetData(SHIFTINFO_CACHE_KEY, startRowIndex + 1, maximumRows, sortExpression, null);
}
public static int GetShiftInfoCount(string searchCriteria)
{
_SupervisorecodeforShift=EmployeeQuotientCL.Entities.StaticGlobalValue.UserId;
int custCount = 0;
try
{
SqlConnection dbConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["DBConnectionString"].ToString());
string sql = "select Count(*)from (select distinct MP.userecode,UI.username,UI.ShiftStartTime,UI.ShiftEndTime,UI.WeekendShiftStartTime,UI.weekendshiftendtime from AssociateSupervisorMapping MP inner join UserInfo UI on MP.Userecode=UI.Userecode where supervisorecode="+_SupervisorecodeforShift.ToString()+")AS internalQuery";
if (!string.IsNullOrEmpty(searchCriteria))
sql = sql + " where " + searchCriteria;
SqlCommand sqlCommand = new SqlCommand(sql, dbConnection);
sqlCommand.Connection = dbConnection;
dbConnection.Open();
sqlCommand.CommandType = CommandType.Text;
custCount = Convert.ToInt32(sqlCommand.ExecuteScalar());
dbConnection.Close();
if (ShiftInfoDBCache.Get(SHIFTINFOCOUNT_CACHE_KEY) != null)
{
// remove customers data if customers count has changed since first cache
if (Convert.ToInt32(ShiftInfoDBCache.Get(SHIFTINFOCOUNT_CACHE_KEY)) != custCount && string.IsNullOrEmpty(searchCriteria))
{
ShiftInfoDBCache.Remove(SHIFTINFO_CACHE_KEY);
}
}
if (string.IsNullOrEmpty(searchCriteria))
ShiftInfoDBCache.Add(SHIFTINFOCOUNT_CACHE_KEY, custCount);
}
catch (Exception e)
{
throw;
}
return custCount;
}
public static void UpdateShift(string sql)
{
SqlConnection dbConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["DBConnectionString"].ToString());
SqlCommand sqlCommand = new SqlCommand(sql, dbConnection);
sqlCommand.CommandType=CommandType.Text;
sqlCommand.CommandText=sql;
dbConnection.Open();
sqlCommand.Connection = dbConnection;
//sqlCommand.CommandType = CommandType.Text;
sqlCommand.ExecuteNonQuery();
dbConnection.Close();
}
}
ShiftInfoDBCache.cs
public class ShiftInfoDBCache
{
public static bool isRecordsCached(string cacheKey)
{
Cache dbCache = HttpContext.Current.Cache;
if (dbCache[cacheKey] == null)
return false;
return true;
}
public static void Add(string key, object value)
{
Cache dbCache = HttpContext.Current.Cache;
dbCache.Add(key, value, null, Cache.NoAbsoluteExpiration, Cache.NoSlidingExpiration, CacheItemPriority.Default, null);
}
public static object Get(string key)
{
Cache dbCache = HttpContext.Current.Cache;
return dbCache[key];
}
public static object Remove(string key)
{
Cache dbCache = HttpContext.Current.Cache;
return dbCache.Remove(key);
}
public static DataTable GetData(string cacheKey, int startRowIndex, int maximumRowNumber, string sortExpression, string searchCriteria)
{
Cache dbCache = HttpContext.Current.Cache;
if (dbCache[cacheKey] != null)
{
DataTable dtble = dbCache[cacheKey] as DataTable;
DataTable dtblNew = dtble.Clone();
DataRow[] rows = dtble.Select(searchCriteria, sortExpression);
if (rows != null)
{
if (rows.Count() > 0)
{
if (startRowIndex > rows.Count())
{
startRowIndex = rows.Count() - maximumRowNumber;
if (startRowIndex < 0)
{
startRowIndex = 1;
maximumRowNumber = rows.Count();
}
}
for (int i = startRowIndex - 1; i < (startRowIndex + maximumRowNumber - 1); i++)
{
if (i < rows.Count())
dtblNew.ImportRow(rows[i]);
}
return dtblNew;
}
}
return dtblNew;
}
return null;
}
}
public static void UpdateShift(string sql)
{
SqlConnection dbConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["DBConnectionString"].ToString());
SqlCommand sqlCommand = new SqlCommand(sql, dbConnection);
sqlCommand.CommandType=CommandType.Text;
sqlCommand.CommandText=sql;
dbConnection.Open();
sqlCommand.Connection = dbConnection;
//sqlCommand.CommandType = CommandType.Text;
sqlCommand.ExecuteNonQuery();
dbConnection.Close();
ShiftInfoDBCache.Remove(SHIFTINFO_CACHE_KEY);
}
Modifying UpdateShift Method in ShiftInfoDB.cs fixed my issue.

Categories