Related
I don't know what's wrong with the code i've tried to search for possible reasons but haven't figured out yet what's the problem actually.Now the issue is that my web form contains a gridview in which i've place a footer row which will allow the user to add the data and that data gets added to the database and gets binded to the gridview after clicking on the insert link button,But the problem comes when i fill the data and when press link button insert it adds the data twice in gridview and in database too everytime.Below is my whole code which is performing CRUD operation on gridview:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm2.aspx.cs" Inherits="WebApplication5.WebForm2" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<asp:Label ID="lblMessage" runat="server" ForeColor="Green" EnableViewState="false" />
<asp:GridView ID="GridView1" runat="server" CellPadding="4" ForeColor="#333333" GridLines="None"
AutoGenerateColumns="false" Width="100%" OnRowEditing="GridView1_RowEditing" OnRowCancelingEdit="GridView1_RowCancelingEdit"
OnRowUpdating="GridView1_RowUpdating" DataKeyNames="AutoId" OnRowDeleting="GridView1_RowDeleting" AllowPaging="true"
PageSize="10" OnPageIndexChanging="GridView1_PageIndexChanging" ShowFooter="True" OnRowCreated="GridView1_RowCreated" OnRowCommand="GridView1_RowCommand">
<Columns>
<asp:TemplateField HeaderText="Edit">
<ItemTemplate>
<asp:LinkButton ID="lnkEdit" runat="server" Text="Edit" CommandName="Edit" />
</ItemTemplate>
<EditItemTemplate>
<asp:LinkButton ID="lnkUpdate" runat="server" Text="Update" CommandName="Update" />
<asp:LinkButton ID="lnkCancel" runat="server" Text="Cancel" CommandName="Cancel" />
</EditItemTemplate>
<FooterTemplate>
<asp:LinkButton ID="lnkBtnInsert" runat="server"
CommandName="Insert">Insert</asp:LinkButton>
</FooterTemplate>
</asp:TemplateField>
<asp:BoundField HeaderText="AutoId" DataField="AutoId" ReadOnly="true" />
<asp:TemplateField HeaderText="First Name">
<ItemTemplate>
<%# Eval("FirstNAme") %>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtFirstName" runat="server" Text='<%# Eval("FirstName") %>' />
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Last Name">
<ItemTemplate>
<%# Eval("LastName") %>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtLastName" runat="server" Text='<%# Eval("LastName") %>' />
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtlname" runat="server"></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Age">
<ItemTemplate>
<%# Eval("Age") %>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtAge" runat="server" Text='<%# Eval("Age") %>' Columns="3" />
<asp:RequiredFieldValidator ID="REw" runat="server" ControlToValidate="txtAge" Text="*" />
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtlage" runat="server"></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Is Active?">
<ItemTemplate>
<%# Eval("Active").ToString().Equals("True") ? "Yes" : "No" %>
</ItemTemplate>
<HeaderStyle HorizontalAlign="Left" />
<EditItemTemplate>
<asp:DropDownList ID="dropActive" runat="server" SelectedValue='<%# Eval("Active") %>'>
<asp:ListItem Text="Yes" Value="True" />
<asp:ListItem Text="No" Value="False" />
</asp:DropDownList>
</EditItemTemplate>
<FooterTemplate>
<asp:DropDownList ID="ddlactive" runat="server">
<asp:ListItem Text="Yes" Value="True" Selected="True"></asp:ListItem>
<asp:ListItem Text="No" Value="False"></asp:ListItem>
</asp:DropDownList>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Delete?">
<ItemTemplate>
<span onclick="return confirm('Are you sure to delete?')">
<asp:LinkButton ID="lnkDelete" runat="server" Text="Delete" ForeColor="Red" CommandName="Delete" />
</span>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<AlternatingRowStyle BackColor="White" />
<EditRowStyle BackColor="#efefef" />
<FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
<RowStyle BackColor="#EFF3FB" HorizontalAlign="Center" />
<SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
<SortedAscendingCellStyle BackColor="#F5F7FB" />
<SortedAscendingHeaderStyle BackColor="#6D95E1" />
<SortedDescendingCellStyle BackColor="#E9EBEF" />
<SortedDescendingHeaderStyle BackColor="#4870BE" />
</asp:GridView>
</form>
</body>
</html>
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.Configuration;
using System.Data;
namespace WebApplication5
{
public partial class WebForm2 : System.Web.UI.Page
{
string _connStr = ConfigurationManager.ConnectionStrings["ConnStr"].ConnectionString;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
PopulateData();
}
}
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
this.PopulateData();
}
protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
GridView1.EditIndex = -1;
this.PopulateData();
}
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
var autoID = GridView1.DataKeys[e.RowIndex].Value;
using (SqlConnection conn = new SqlConnection(_connStr))
{
string sql = "Delete from PersonalDetail" +
" where AutoId = #AutoId";
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
cmd.Parameters.AddWithValue(
"#AutoId", autoID);
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
}
}
lblMessage.Text =
"Record has been deleted successfully !";
lblMessage.ForeColor = System.Drawing.
Color.Red;
this.PopulateData();
}
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
this.PopulateData();
}
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
var autoID = GridView1.DataKeys[e.RowIndex].Value;
GridViewRow row = GridView1.Rows[e.RowIndex] as GridViewRow;
TextBox tFirstName = row.FindControl("txtFirstName") as TextBox;
TextBox tLastName = row.FindControl("txtLastName") as TextBox;
TextBox tAge = row.FindControl("txtAge") as TextBox;
DropDownList dropActive = row.FindControl("dropActive") as DropDownList;
using (SqlConnection conn = new SqlConnection(_connStr))
{
string sql = "Update PersonalDetail set FirstName = #FirstName,LastName=#LastName, Age= #Age, Active = #Active" + " where AutoId = #AutoId";
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
cmd.Parameters.AddWithValue(
"#FirstName", tFirstName.Text.Trim());
cmd.Parameters.AddWithValue(
"#LastName", tLastName.Text.Trim());
cmd.Parameters.AddWithValue(
"#Age", tAge.Text.Trim());
cmd.Parameters.AddWithValue(
"#Active", dropActive.SelectedValue);
cmd.Parameters.AddWithValue(
"#AutoId", autoID);
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
}
}
lblMessage.Text =
"Record updated successfully !";
GridView1.EditIndex = -1;
this.PopulateData();
}
private void PopulateData()
{
DataTable table = new DataTable();
using (SqlConnection conn = new SqlConnection(_connStr))
{
string sql = "Select * from PersonalDetail";
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
using (SqlDataAdapter ad = new SqlDataAdapter(cmd))
{
ad.Fill(table);
}
}
}
GridView1.DataSource = table;
GridView1.DataBind();
}
protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
{
}
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName.Equals("Insert"))
{
TextBox name = (TextBox)GridView1.FooterRow.FindControl("TextBox1");
TextBox lname = (TextBox)GridView1.FooterRow.FindControl("txtlname");
TextBox age = (TextBox)GridView1.FooterRow.FindControl("txtlage");
DropDownList isactive = (DropDownList)GridView1.FooterRow.FindControl("ddlactive");
using(SqlConnection conn = new SqlConnection(_connStr))
{
SqlCommand cmd = new SqlCommand("INSERT INTO PersonalDetail(FirstName,LastName,Age,Active) VALUES('" + name.Text + "','" + lname.Text + "','" + age.Text + "','" + isactive.SelectedItem.Value + "')",conn);
cmd.CommandType = CommandType.Text;
conn.Open();
cmd.ExecuteNonQuery();
//int result = cmd.ExecuteNonQuery();
conn.Close();
}
}
lblMessage.Text =
"Record has been Added successfully !";
this.PopulateData();
}
}
}
Please try below code :
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
GridView1.RowCommand -= GridView1_RowCommand;
if (e.CommandName.Equals("Insert"))
{
TextBox name = (TextBox)GridView1.FooterRow.FindControl("TextBox1");
TextBox lname = (TextBox)GridView1.FooterRow.FindControl("txtlname");
TextBox age = (TextBox)GridView1.FooterRow.FindControl("txtlage");
DropDownList isactive = (DropDownList)GridView1.FooterRow.FindControl("ddlactive");
using(SqlConnection conn = new SqlConnection(_connStr))
{
SqlCommand cmd = new SqlCommand("INSERT INTO PersonalDetail(FirstName,LastName,Age,Active) VALUES('" + name.Text + "','" + lname.Text + "','" + age.Text + "','" + isactive.SelectedItem.Value + "')",conn);
cmd.CommandType = CommandType.Text;
conn.Open();
cmd.ExecuteNonQuery();
//int result = cmd.ExecuteNonQuery();
conn.Close();
}
}
lblMessage.Text =
"Record has been Added successfully !";
this.PopulateData();
}
Hi I have used gridview to create a table.
Is there a way to implement edit and delete.
I have done it in PHP before. The method I would like to use is create two more columns in the table with edit and delete buttons on each row. Then when the buttons are click it passes the 'id' through the URL and able to edit or delete. Not really sure how to do this in asp.net webforms. Below is my code for the table. Thank you.
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:BoundField HeaderText="Surgery" DataField="surgery" />
<asp:BoundField HeaderText="PatientID" DataField="patientID" />
<asp:BoundField HeaderText="Location" DataField="location" />
</Columns>
SqlCommand cmd = new SqlCommand("select surgery, patientID, location from details", conn);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
sda.Fill(dt);
conn.Close();
GridView1.DataSource = dt;
GridView1.DataBind();
The GridView supports those operations. You can add a CommandField which will contain the command buttons or LinkButtons (you can choose the type of button and assign the text of each button). The patientID field should be included in the DataKeyNames property of the GridView, in order to retrieve it when the time comes to update or delete the record in the database.
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false"
DataKeyNames="patientID"
OnRowEditing="GridView1_RowEditing" OnRowCancelingEdit="GridView1_RowCancelingEdit"
OnRowUpdating="GridView1_RowUpdating" OnRowDeleting="GridView1_RowDeleting" >
<Columns>
<asp:CommandField ShowEditButton="true" ShowCancelButton="true" ShowDeleteButton="true" />
<asp:BoundField HeaderText="Surgery" DataField="surgery" />
...
</Columns>
You will then need to handle a few events in code-behind:
// The RowEditing event is called when data editing has been requested by the user
// The EditIndex property should be set to the row index to enter edit mode
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
BindData();
}
// The RowCancelingEdit event is called when editing is canceled by the user
// The EditIndex property should be set to -1 to exit edit mode
protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
GridView1.EditIndex = -1;
BindData();
}
// The RowUpdating event is called when the Update command is selected by the user
// The EditIndex property should be set to -1 to exit edit mode
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
int patientID = (int)e.Keys["patientID"]
string surgery = (string)e.NewValues["surgery"];
string location = (string)e.NewValues["location"];
// Update here the database record for the selected patientID
GridView1.EditIndex = -1;
BindData();
}
// The RowDeleting event is called when the Delete command is selected by the user
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
int patientID = (int)e.Keys["patientID"]
// Delete here the database record for the selected patientID
BindData();
}
Since the data must be bound to the GridView at the end of each of those event handlers, you can do it in a BindData utility function, which should also be called when the page loads initially:
private void BindData()
{
SqlCommand cmd = new SqlCommand("select surgery, patientID, location from details", conn);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
sda.Fill(dt);
conn.Close();
GridView1.DataSource = dt;
GridView1.DataBind();
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindData();
}
}
And Store Procedure is:
USE [DemoProjet]
GO
/****** Object: StoredProcedure [dbo].[Customers_CRUD] Script Date: 11-Jan-17 2:57:38 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[Customers_CRUD]
#Action VARCHAR(10)
,#BId INT = NULL
,#Username VARCHAR(50) = NULL
,#Provincename VARCHAR(50) = NULL
,#Cityname VARCHAR(50) = NULL
,#Number VARCHAR(50) = NULL
,#Name VARCHAR(50) = NULL
,#ContentType VARCHAR(50) = NULL
,#Data VARBINARY(MAX) = NULL
AS
BEGIN
SET NOCOUNT ON;
--SELECT
IF #Action = 'SELECT'
BEGIN
SELECT BId , Username,Provincename,Cityname,Number,Name,ContentType, Data
FROM tblbooking
END
--INSERT
IF #Action = 'INSERT'
BEGIN
INSERT INTO tblbooking(Username,Provincename,Cityname,Number,Name,ContentType, Data)
VALUES (#Username ,#Provincename ,#Cityname ,#Number ,#Name ,#ContentType ,#Data)
END
--UPDATE
IF #Action = 'UPDATE'
BEGIN
UPDATE tblbooking
SET Username = #Username,Provincename = #Provincename,Cityname = #Cityname,Number = #Number,Name = #Name,ContentType = #ContentType,Data = #Data
WHERE BId = #BId
END
--DELETE
IF #Action = 'DELETE'
BEGIN
DELETE FROM tblbooking
WHERE BId = #BId
END
END
GO
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.Configuration;
using System.Data.SqlClient;
namespace FinalYearProject
{
public partial class MBooking : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
this.BindGrid();
}
}
private void BindGrid()
{
string constr = ConfigurationManager.ConnectionStrings["cmt"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("Customers_CRUD"))
{
cmd.Parameters.AddWithValue("#Action", "SELECT");
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Connection = con;
sda.SelectCommand = cmd;
using (DataTable dt = new DataTable())
{
sda.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
}
}
}
protected void Insert(object sender, EventArgs e)
{
string Username = txtUsername.Text;
string Provincename = txtProvinceName.Text;
string Cityname = txtCityname.Text;
string Number = txtNumber.Text;
string Name = txtName.Text;
string ContentType = txtContentType.Text;
string Data = txtData.Text;
string constr = ConfigurationManager.ConnectionStrings["cmt"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("Customers_CRUD"))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#Action", "INSERT");
cmd.Parameters.AddWithValue("#Username", Username);
cmd.Parameters.AddWithValue("#Provincename ", Provincename);
cmd.Parameters.AddWithValue("#Cityname", Cityname);
cmd.Parameters.AddWithValue("#Number", Number);
cmd.Parameters.AddWithValue("#Name", Name);
cmd.Parameters.AddWithValue("#ContentType", ContentType);
//cmd.Parameters.AddWithValue("#Data", Data);
cmd.Parameters.AddWithValue("#Data", SqlDbType.VarBinary).Value = new Byte[] { 0xDE, 0xAD, 0xBE, 0xEF };
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
this.BindGrid();
}
protected void OnRowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
this.BindGrid();
}
protected void OnRowCancelingEdit(object sender, EventArgs e)
{
GridView1.EditIndex = -1;
this.BindGrid();
}
protected void OnRowUpdating(object sender, GridViewUpdateEventArgs e)
{
GridViewRow row = GridView1.Rows[e.RowIndex];
int BId = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Values[0]);
string Username = (row.FindControl("txtUserName") as TextBox).Text;
string Provincename = (row.FindControl("txtProvincename") as TextBox).Text;
string Cityname = (row.FindControl("txtCityname") as TextBox).Text;
string Number = (row.FindControl("txtNumber") as TextBox).Text;
string Name = (row.FindControl("txtName") as TextBox).Text;
string ContentType = (row.FindControl("txtContentType") as TextBox).Text;
string Data = (row.FindControl("txtData") as TextBox).Text;
string constr = ConfigurationManager.ConnectionStrings["cmt"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("Customers_CRUD"))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#Action", "UPDATE");
cmd.Parameters.AddWithValue("#BId", BId);
cmd.Parameters.AddWithValue("#Username", Username);
cmd.Parameters.AddWithValue("#Provincename ", Provincename);
cmd.Parameters.AddWithValue("#Cityname", Cityname);
cmd.Parameters.AddWithValue("#Number", Number);
cmd.Parameters.AddWithValue("#Name", Name);
cmd.Parameters.AddWithValue("#ContentType",ContentType) ;
cmd.Parameters.AddWithValue("#Data", SqlDbType.VarBinary).Value = new Byte[] { 0xDE, 0xAD, 0xBE, 0xEF };
//cmd.Parameters.AddWithValue("#ContentType", SqlDbType.VarBinary, -1);
//cmd.Parameters.AddWithValue("#Data", SqlDbType.VarBinary, -1);
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
GridView1.EditIndex = -1;
this.BindGrid();
}
protected void OnPageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
this.BindGrid();
}
protected void OnRowDataBound(object sender, GridViewRowEventArgs e)
{
//if (e.Row.RowType == DataControlRowType.DataRow && e.Row.RowIndex != GridView1.EditIndex)
//{
// (e.Row.Cells[2].Controls[2] as LinkButton).Attributes["onclick"] = "return confirm('Do you want to delete this row?');";
//}
}
protected void DownloadFile(object sender, EventArgs e)
{
int id = int.Parse((sender as LinkButton).CommandArgument);
byte[] bytes;
string fileName, contentType;
string constr = ConfigurationManager.ConnectionStrings["cmt"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = "select Name, Data, ContentType from tblbooking where BId=#BId";
cmd.Parameters.AddWithValue("#BId",id);
cmd.Connection = con;
con.Open();
using (SqlDataReader sdr = cmd.ExecuteReader())
{
sdr.Read();
bytes = (byte[])sdr["Data"];
contentType = sdr["ContentType"].ToString();
fileName = sdr["Name"].ToString();
}
con.Close();
}
}
Response.Clear();
Response.Buffer = true;
Response.Charset = "";
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = contentType;
Response.AppendHeader("Content-Disposition", "attachment; filename=" + fileName);
Response.BinaryWrite(bytes);
Response.Flush();
Response.End();
}
protected void OnRowDeleting(object sender, GridViewDeleteEventArgs e)
{
int BId = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Values[0]);
string constr = ConfigurationManager.ConnectionStrings["cmt"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("Customers_CRUD"))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#Action", "DELETE");
cmd.Parameters.AddWithValue("#BId", BId);
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
this.BindGrid();
}
}
}
And Aspx page is:
<%# Page Title="" Language="C#" MasterPageFile="~/admin.Master" AutoEventWireup="true" CodeBehind="MBooking.aspx.cs" Inherits="FinalYearProject.MBooking" %>
<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
<style type="text/css">
<%-- body
{
font-family: Arial;
font-size: 10pt;
}
table
{
border: 1px solid #ccc;
border-collapse: collapse;
background-color: #fff;
}
table th
{
background-color: #B8DBFD;
color: #333;
font-weight: bold;
}
table th, table td
{ background-color: #B8DBFD;
padding: 5px;
border: 1px solid #ccc;
}
table, table table td
{
border: 3px solid #ccc;
}
--%>
.style1
{
width: 184px;
}
</style>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" AllowPaging="True"
OnPageIndexChanging="OnPageIndexChanging" PageSize="6" DataKeyNames="BId"
OnRowDataBound="OnRowDataBound" OnRowEditing="OnRowEditing" OnRowCancelingEdit="OnRowCancelingEdit"
OnRowUpdating="OnRowUpdating" OnRowDeleting="OnRowDeleting"
EmptyDataText="No records has been added."
Style="margin:20px 0px 0px 25px;" BackColor="White" BorderColor="#3366CC"
BorderStyle="None" BorderWidth="1px" CellPadding="4" Height="250px"
Width="1035px" >
<Columns>
<asp:TemplateField HeaderText="Username" ItemStyle-Width="120">
<ItemTemplate>
<asp:Label ID="lblUsername" runat="server" Text='<%# Eval("Username") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtUsername" style = "Width:100px;" runat="server" Text='<%# Eval("Username") %>'></asp:TextBox>
</EditItemTemplate>
<ItemStyle Width="120px"></ItemStyle>
</asp:TemplateField>
<asp:TemplateField HeaderText="ProvinceName" ItemStyle-Width="120">
<ItemTemplate>
<asp:Label ID="lblProvinceName" runat="server" Text='<%# Eval("Provincename") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtProvinceName" style = "Width:100px;" runat="server" Text='<%# Eval("Provincename") %>'></asp:TextBox>
</EditItemTemplate>
<ItemStyle Width="120px"></ItemStyle>
</asp:TemplateField>
<asp:TemplateField HeaderText="CityName" ItemStyle-Width="120">
<ItemTemplate>
<asp:Label ID="lblCityname" runat="server" Text='<%# Eval("Cityname") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtCityname" style = "Width:100px;" runat="server" Text='<%# Eval("Cityname") %>'></asp:TextBox>
</EditItemTemplate>
<ItemStyle Width="120px"></ItemStyle>
</asp:TemplateField><asp:TemplateField HeaderText="Number" ItemStyle-Width="120">
<ItemTemplate>
<asp:Label ID="lblNumber" runat="server" Text='<%# Eval("Number") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtNumber" style = "Width:100px;" runat="server" Text='<%# Eval("Number") %>'></asp:TextBox>
</EditItemTemplate>
<ItemStyle Width="120px"></ItemStyle>
</asp:TemplateField><asp:TemplateField HeaderText="Name" ItemStyle-Width="120">
<ItemTemplate>
<asp:Label ID="lblName" runat="server" Text='<%# Eval("Name") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtName" style = "Width:100px;" runat="server" Text='<%# Eval("Name") %>'></asp:TextBox>
</EditItemTemplate>
<ItemStyle Width="120px"></ItemStyle>
</asp:TemplateField><asp:TemplateField HeaderText="ContentType" ItemStyle-Width="120">
<ItemTemplate>
<asp:Label ID="lblContentType" runat="server" Text='<%# Eval("ContentType") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtContentType" style = "Width:100px;" runat="server" Text='<%# Eval("ContentType") %>'></asp:TextBox>
</EditItemTemplate>
<ItemStyle Width="120px"></ItemStyle>
</asp:TemplateField><asp:TemplateField HeaderText="Data" ItemStyle-Width="120">
<ItemTemplate>
<asp:Label ID="lblData" runat="server" Text='<%# Eval("Data") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtData" style = "Width:100px;" runat="server" Text='<%# Eval("Data") %>'></asp:TextBox>
</EditItemTemplate>
<ItemStyle Width="120px"></ItemStyle>
</asp:TemplateField>
<asp:TemplateField> <ItemTemplate>
<asp:LinkButton ID="lnkDownload" runat="server" Text="Download" OnClick="DownloadFile"
CommandArgument='<%# Eval("BId") %>'></asp:LinkButton>
</ItemTemplate></asp:TemplateField>
<asp:CommandField ButtonType="Link" ShowEditButton="true" ShowDeleteButton="true"
ItemStyle-Width="100" >
<ItemStyle Width="100px"></ItemStyle>
</asp:CommandField>
</Columns>
<FooterStyle BackColor="#99CCCC" ForeColor="#003399" />
<HeaderStyle BackColor="#003399" Font-Bold="True" ForeColor="#CCCCFF" />
<PagerStyle BackColor="#99CCCC" ForeColor="#003399" HorizontalAlign="Center"
Font-Bold="True" Font-Italic="True" Font-Underline="True" Width="20px" />
<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>
<br />
<table border="1" cellpadding="0" cellspacing="0" style="border-collapse: collapse; margin:10px 0px 0px 25px;">
<tr>
<td style="width: 100px; background-color:#003399; color:#CCCCFF;">
<b> Username:</b><br />
<asp:TextBox ID="txtUsername" runat="server" Width="120" />
</td>
<td style="width: 100px;background-color:#003399; color:#CCCCFF;">
<b> Provincename:</b><br />
<asp:TextBox ID="txtProvinceName" runat="server" Width="120" />
</td>
<td style="width: 100px;background-color:#003399; color:#CCCCFF;">
<b>Cityname:</b><br />
<asp:TextBox ID="txtCityname" runat="server" Width="120" />
</td>
<td style="width: 100px;background-color:#003399; color:#CCCCFF;">
<b> Number:</b><br />
<asp:TextBox ID="txtNumber" runat="server" Width="120" />
</td>
<td style="width: 100px;background-color:#003399; color:#CCCCFF;">
<b> Name:</b><br />
<asp:TextBox ID="txtName" runat="server" Width="120" />
</td>
<td style="width: 100px;background-color:#003399; color:#CCCCFF;">
<b> ContentType:</b><br />
<asp:TextBox ID="txtContentType" runat="server" Width="120" />
</td>
<td style="width: 100px;background-color:#003399; color:#CCCCFF;">
<b>Data:</b><br />
<asp:TextBox ID="txtData" runat="server" Width="120" />
</td>
<td style="background-color:#003399; color:#CCCCFF;" class="style1">
<asp:Button ID="btnAdd" runat="server" CssClass="btn btn-info" Text="Add"
OnClick="Insert" Width="187px" />
</td>
</tr>
</table>
</asp:Content>
I have created a gridview, for the user to add/edit and remove products. (not actually deleting but declaring it discontinued on the database)
I am getting the following exception:
An exception of type 'System.FormatException' occurred in mscorlib.dll
but was not handled in user code
My markup is as follows:
<%# Page Title="" Language="C#" MasterPageFile="~/Admin/AdminMaster.master" AutoEventWireup="true" CodeFile="addProduct.aspx.cs" Inherits="Admin_addProduct" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="Server">
</asp:Content>
<asp:Content ID="Content3" ContentPlaceHolderID="RightCol" runat="Server">
<h1>Products</h1>
<asp:Label ID="lblProdGrd" runat="server"></asp:Label>
<asp:SqlDataSource ID="lstCatSrc" runat="server" ConnectionString='<%$ ConnectionStrings:bncConn %>' SelectCommand="SELECT CategoryName, CategoryId FROM ProductDetails.Category"></asp:SqlDataSource>
<asp:SqlDataSource ID="lstSubCatSrc" runat="server" ConnectionString='<%$ ConnectionStrings:bncConn %>' SelectCommand="SELECT ProductType, ProductTypeId FROM ProductDetails.ProductType"></asp:SqlDataSource>
<asp:SqlDataSource ID="lstImgSrc" runat="server" ConnectionString='<%$ ConnectionStrings:bncConn %>' SelectCommand="SELECT ImageName, ImageId, ImagePath FROM ProductDetails.ProductImages"></asp:SqlDataSource>
<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"
onrowdeleting="grdProds_RowDeleting">
<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='<%# Bind("Price") %>' TextMode="Number"></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" DataSourceID="lstCatSrc" DataTextField="CategoryName" DataValueField="CategoryId" AppendDataBoundItems="True">
<asp:ListItem Text="--(Select a category)--" Value="NULL"></asp:ListItem>
</asp:DropDownList>
</EditItemTemplate>
<FooterTemplate>
<asp:DropDownList ID="lstCat" runat="server" DataSourceID="lstCatSrc" DataTextField="CategoryName" DataValueField="CategoryId" AppendDataBoundItems="True">
<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" DataSourceID="lstSubCatSrc" DataTextField="ProductType" DataValueField="ProductTypeId"></asp:DropDownList>
</EditItemTemplate>
<FooterTemplate>
<asp:DropDownList ID="lstAddSubCat" runat="server" DataSourceID="lstSubCatSrc" DataTextField="ProductType" DataValueField="ProductTypeId"></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" DataSourceID="lstImgSrc" DataTextField="ImageName" DataValueField="ImageId"></asp:DropDownList>
<asp:Image ID="imgProdEdit" runat="server" Height="250" Width="250" />
</EditItemTemplate>
<FooterTemplate>
<asp:DropDownList ID="lstAddProdImg" runat="server" DataSourceID="lstImgSrc" DataTextField="ImageName" DataValueField="ImageId"></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:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Globalization;
using System.Data;
using System.Data.SqlTypes;
using System.Data.SqlClient;
using System.Web.Configuration;
using System.Data.Entity;
using BillyNicClothingModel;
public partial class Admin_addProduct : System.Web.UI.Page
{
private string connectionString =
WebConfigurationManager.ConnectionStrings["bncConn"].ConnectionString;
string CatLst;
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;
int Category, Image;
bool InStock, Preprinted;
decimal Price;
byte SubCat;
ProductName = txtName.Text;
Description = txtDescription.Text;
Price = Decimal.Parse(txtPrice.Text);
Category = int.Parse(lstCatEdit.SelectedValue);
SubCat = byte.Parse(lstSubCat.SelectedValue);
Image = int.Parse(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, decimal Price, int Category, int SubCat,
int 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", SqlDbType.VarChar, 50));
cmd.Parameters["#status"].Value = "Add";
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");
int pId = Convert.ToInt32(prId.Text);
DeleteProduct(pId);
grdProds.EditIndex = -1;
BindGrid();
}
protected void DeleteProduct(int 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");
int ProdId = Convert.ToInt32(prdId.Text);
string eName = Name.Text;
string eDescription = Description.Text;
Decimal ePrice = Convert.ToDecimal(Price.Text);
int eCat = Convert.ToInt32(Category.SelectedValue);
byte eSCat = Convert.ToByte(SubCat.SelectedValue);
int eImage = Convert.ToInt32(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(int ProdId, string eName, string eDescription, Decimal ePrice, int eCat, byte eSCat, int 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 = Convert.ToInt32(ProdId);
cmd.Parameters.Add(new SqlParameter("#Status", SqlDbType.VarChar, 50));
cmd.Parameters["#Status"].Value = "Update";
cmd.Parameters.Add(new SqlParameter("#ProductName", SqlDbType.VarChar, 50));
cmd.Parameters["#ProductName"].Value = eName;
cmd.Parameters.Add(new SqlParameter("#Description", SqlDbType.VarChar, -1));
cmd.Parameters["#description"].Value = eDescription;
cmd.Parameters.Add(new SqlParameter("#Price", SqlDbType.Money));
cmd.Parameters["#Price"].Value = ePrice;
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 = 0,
#Category int = 0,
#ProductType tinyint = 0,
#Price money = 0,
#InStock bit = 1,
#ProductName varchar(50) = '',
#Image int = 0,
#Description varchar(max) = '',
#PrePrinted bit = 1,
#Discontinued bit = 0,
#Status varchar(50) = ''
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
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
Also when I try to delete a product, well declare it to be discontinued, nothing seems to happen and if anyone is able to point out where and what is wrong I would be very grateful as I am at a total loss as to what's going on. Sorry if any of this seems a little vague, I'm quite the novice at this, and so am at a complete standstill at the moment. Thank you in advanced to anyone willing to help.
You getting System.FormatException as have opened the following asp:content but have not closed it:
<asp:content id="Content3" contentplaceholderid="RightCol" runat="Server">
So after </asp:GridView> put </asp:content> and delete function will get executed.
I have a GridView that has a column named Run Time and it uses TextBoxes rTime. I'm going to be bewing this GridView on an andriod operating system and want it to pull a keypad if someone clicks on the textbox. This has worked before without the GridView, but I've been getting a The name 'rTime' does not exist in the current context error. Here is my aspx code: `
<asp:TemplateField HeaderText="labelID" Visible="false">
<ItemTemplate>
<asp:Label ID="ID" runat="server" Text='<%# Eval("Id") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="First Name">
<ItemTemplate>
<asp:Label ID="labelfirstname" Visible="true" runat="server" Text='<%# Eval("fName") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Last Name">
<ItemTemplate>
<asp:Label ID="labellastname" Visible="true" runat="server" Text='<%# Eval("lName") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Run Time Needed">
<ItemTemplate>
<asp:Label ID="labelrTimeN" Visible="true" runat="server" Text='<%# Eval("rTimeN") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Run Time">
<ItemTemplate>
<div style="display:none"><asp:TextBox ID="rTime" runat="server" Height="16px"
ontextchanged="TextBox1_TextChanged" Width="108px"></asp:TextBox></div>
<span class="style4"><strong>Meter Run:</strong></span><span class="style5"> </span><input onblur="document.getElementById('<%=rTime.ClientID %>').value = this.value"
type="tel" style="width: 100px; height: 31px;" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>`
Here is c#:
private bool isEditMode = false;
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
BindData();
}
UpdatePanel1.Visible = false;
}
private void BindData()
{
string connectiongString = "Data Source=WSCJTCSQ1;Initial Catalog=TestDB;Persist Security Info=True;User ID=v2soft;Password=passwordv2soft";
SqlConnection myConnection = new SqlConnection(connectiongString);
SqlDataAdapter ad = new SqlDataAdapter("SELECT Id, fName, lName, rTimeN, rTime FROM bleaTest", myConnection);
DataSet ds = new DataSet();
ad.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
}
protected void Button1_Click(object sender, EventArgs e)
{
isEditMode = true;
UpdatePanel1.Visible = true;
BindData();
}
protected void TextBox1_TextChanged(object sender, EventArgs e)
{
}
protected void Button2_Click(object sender, EventArgs e)
{
Update();
}
protected bool IsInEditMode
{
get { return this.isEditMode; }
set { this.isEditMode = value; }
}
private void Update()
{
StringBuilder sb = new StringBuilder();
foreach (GridViewRow row in GridView1.Rows)
{
sb.Append("UPDATE bleaTest SET rTime = '");
sb.Append((row.FindControl("rTime") as TextBox).Text);
sb.Append("'");
sb.Append(" WHERE id = ");
sb.Append(Convert.ToInt32((row.FindControl("ID") as Label).Text));
sb.Append(" ");
}
string connectiongString = "Data Source=WSCJTCSQ1;Initial Catalog=TestDB;Persist Security Info=True;User ID=v2soft;Password=passwordv2soft";
SqlConnection myConnection = new SqlConnection(connectiongString);
SqlCommand myCommand = new SqlCommand(sb.ToString(), myConnection);
myConnection.Open();
myCommand.ExecuteNonQuery();
myConnection.Close();
isEditMode = false;
BindData();
UpdatePanel1.Visible = false;
}
protected void gvUsers_RowDataBound(object sender, GridViewCommandEventArgs e)
{
}
Thank you in advance!!
Did some more research and re-wrote the code a little. Here's the update:
<asp:TemplateField HeaderText="Run Time">
<ItemTemplate>
<div style="display:none"> <asp:TextBox ID="rTime" runat="server" type="number" Text='<%# Eval("rTime") %>' ></asp:TextBox></div>
<input onblur="document.getElementById('<%# ((GridViewRow)Container).FindControl("rTime").ClientID %>').value = this.value"
type="tel" style="width: 100px; height: 31px;" />
</ItemTemplate>
<asp:Panel ID="pnlFocusAreaPanel" runat="server" GroupingText="Focus Area" Width="800">
<table cellspacing="0" cellpadding="0" width="750">
<tr>
<td>
<asp:GridView ID="dgFocusAreaDetails" runat="server" Width="100%" CssClass="dgStyle"
AutoGenerateColumns="False" BorderColor="Silver" BorderWidth="1px" CellPadding="0"
ShowHeader="False" OnSelectedIndexChanged="dgFocusAreaDetails_SelectedIndexChanged"
DataKeyNames="PK_ID">
<FooterStyle Font-Underline="True" HorizontalAlign="Center" VerticalAlign="Middle">
</FooterStyle>
<Columns>
<asp:TemplateField HeaderText="Focus Area" HeaderStyle-BackColor="Silver">
<ItemStyle Width="90%" />
<ItemTemplate>
<asp:Label runat="server" ID="lblFocusArea" Text='<%# DataBinder.Eval(Container.DataItem, "FOCUS_AREA_NAME").ToString()%>'>
</asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Is Current Valid" HeaderStyle-BackColor="Silver">
<ItemStyle Width="10%" HorizontalAlign="Center" />
<ItemTemplate>
<asp:CheckBox ID="chkFocusArea" runat="server" OnCheckedChanged="OnCheckChangedEvent"
AutoPostBack="true" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</td>
</tr>
<tr>
<td align="left">
<asp:TextBox ID="txtFocusArea" runat="server" Width="300px" CausesValidation="true" CssClass="txtStyle" ValidationGroup="focusArea">
</asp:TextBox>
<cc1:TextBoxWatermarkExtender ID="txtFocusAreaWaterMark" runat="server" TargetControlID="txtFocusArea"
WatermarkText="Add Focus Area" WatermarkCssClass="WaterMarkStyle">
</cc1:TextBoxWatermarkExtender>
<asp:Button ID="btnAddFocusArea" runat="server" Text="AddFocusArea" CssClass="btnStyle"
OnClick="btnAddFocusArea_Click" CausesValidation="true" ValidationGroup="focusArea" />
<asp:RequiredFieldValidator ID="reqtxtFocusArea" runat="server" ControlToValidate="txtFocusArea"
ErrorMessage="Please enter focus area" Display="Dynamic" ValidationGroup="focusArea">
</asp:RequiredFieldValidator>
<asp:RegularExpressionValidator ID="regexFocusArea" runat="server" ErrorMessage="Invalid characters(<,>,#)"
ControlToValidate="txtFocusArea" ValidationExpression="^([^<#>]*)$" ValidationGroup="focusArea"
Display="Dynamic" SetFocusOnError="true">
</asp:RegularExpressionValidator>
</td>
</tr>
</table>
</asp:Panel>
and in code behind
protected void btnAddFocusArea_Click(object sender, EventArgs e)
{
string strFocusArea = txtFocusArea.Text;
OleDbConnection myConnection = new OleDbConnection(ConfigurationSettings.AppSettings["SQLConnectionString"]);
if (strFocusArea == string.Empty || strFocusArea == txtFocusAreaWaterMark.WatermarkText)
{
lblError.Text = "Focus area is not entered";
}
else
{
string insertQuery = "INSERT INTO LK_CODECAT_FOCUS_AREA(FOCUS_AREA_NAME,FK_ADDED_BY,ADDED_ON) "+
" VALUES('" + strFocusArea + "', "+Session["UserID"] +", GETDATE())";
try
{
myConnection.Open();
OleDbCommand myCommandToInsert = new OleDbCommand(insertQuery, myConnection);
myCommandToInsert.ExecuteNonQuery();
}
catch(Exception exc)
{
ExceptionLogger.LogException(exc);
}
finally
{
if (myConnection != null)
{
myConnection.Close();
}
}
PopulateFocusArea();
}
txtFocusArea.Text = txtFocusAreaWaterMark.WatermarkText;
}
private void PopulateFocusArea()
{
OleDbConnection myConnection = new OleDbConnection(ConfigurationSettings.AppSettings["SQLConnectionString"]);
string selectQuery = "SELECT PK_ID, FOCUS_AREA_NAME, IS_CURRENT_FOCUS FROM LK_CODECAT_FOCUS_AREA LKCFA ORDER BY FOCUS_AREA_NAME";
if (Session["RoleID"].ToString() == "1" || ((Session["WorkID"].ToString() != "9") ||
(Session["WorkID2"].ToString() != "9") ||
(Session["WorkID3"].ToString() != "9")))
{
try
{
myConnection.Open();
OleDbCommand myCommandFocusArea = new OleDbCommand(selectQuery, myConnection);
OleDbDataAdapter myAdapter = new OleDbDataAdapter(myCommandFocusArea);
DataSet ds = new DataSet();
myAdapter.Fill(ds);
dgFocusAreaDetails.DataSource = ds;
dgFocusAreaDetails.ShowHeader = true;
dgFocusAreaDetails.DataBind();
}
catch (Exception exc)
{
ExceptionLogger.LogException(exc);
}
finally
{
if (myConnection != null)
{
myConnection.Close();
}
}
}
}
protected void dgFocusAreaDetails_SelectedIndexChanged(object sender, EventArgs e)
{
string selectedCategory = dgFocusAreaDetails.SelectedRow.Cells[1].Text;
int index = dgFocusAreaDetails.SelectedIndex;
lblError.Text = dgFocusAreaDetails.DataKeys[index].Value.ToString();
}
public void OnCheckChangedEvent(object sender, EventArgs e)
{
CheckBox chk = (CheckBox)sender;
string chkfocusarea = ((Control)chk).ID;
//string focusAreaDetails = dgFocusAreaDetails.SelectedRow.Cells[0].Text;
int index =Convert.ToInt32(dgFocusAreaDetails.SelectedIndex);
if (chk.Checked)
{
string updateQuery = "UPDATE [LK_CODECAT_FOCUS_AREA] SET [IS_CURRENT_FOCUS] = 1 WHERE PK_ID = "
+Convert.ToInt32( dgFocusAreaDetails.DataKeys[index].Value)+" ";
}
else
{
lblError.Text = "unchecked";
}
}
i want to know how i find the datakeyvalue on checked event because updateQuery in checked event is generating exception.
Could you add a asp:button instead of using the checkbox on your GridView and fire an OnRowUpdating event?
Alternatively you could store the index value in a session varaible to pick up on your chkbox click.
edit: found this post is that any help?
They suggest you have to check each row to see if the value has changed.