Saturday, December 31, 2016

Display Images in GridView Control using the path stored in SQL Server database

Show Image in GridView Using ASP.NET



 Display_Image.aspx  
 <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Display_Image.aspx.cs" Inherits="Display_Image" %>  
 <!DOCTYPE html>  
 <html xmlns="http://www.w3.org/1999/xhtml">  
 <head runat="server">  
   <title></title>  
 </head>  
 <body>  
   <form id="form1" runat="server">  
    <h3 style="color: #0000FF; font-style: italic">Display Image in GridView Using ASP.NET</h3>  
   <div>  
   <asp:FileUpload ID="fileupload" runat="server" />  
     <br />  
     <asp:Button ID="upload" runat="server" Font-Bold="true" Text="Upload" OnClick="upload_Click" />  
     <br />  
     <br />  
   </div>  
     <div>  
       <asp:GridView runat="server" ID="gdImage" HeaderStyle-BackColor="Tomato" AutoGenerateColumns="false">  
         <Columns>  
           <asp:BoundField DataField="ImageId" HeaderText="ImageId" />  
           <asp:BoundField DataField="ImageName" HeaderText="ImageName" />  
           <asp:ImageField DataImageUrlField="Image" HeaderText="Image"></asp:ImageField>            
         </Columns>  
       </asp:GridView>  
     </div>  
   </form>  
 </body>  
 </html>  


 Display_Image.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;  
 using System.Data.SqlClient;  
 using System.IO;  
 using System.Configuration;  
 public partial class Display_Image : System.Web.UI.Page  
 {  
   SqlConnection con;  
   SqlDataAdapter da;  
   DataSet ds;  
   SqlCommand cmd;  
   protected void Page_Load(object sender, EventArgs e)  
   {  
   }  
   protected void upload_Click(object sender, EventArgs e)  
   {  
     try  
     {  
       string filename = Path.GetFileName(fileupload.PostedFile.FileName);  
       fileupload.SaveAs(Server.MapPath("~/Images/" + filename));  
       con = new SqlConnection(ConfigurationManager.ConnectionStrings["ImageSql"].ConnectionString);  
       con.Open();  
       cmd = new SqlCommand("insert into Image_Details (ImageName,Image) values(@ImageName,@Image)", con);  
       cmd.Parameters.AddWithValue("@ImageName", filename);  
       cmd.Parameters.AddWithValue("@Image", "Images/" + filename);  
       cmd.ExecuteNonQuery();  
       da = new SqlDataAdapter("select * from Image_Details",con);  
       ds = new DataSet();  
       da.Fill(ds);  
       gdImage.DataSource = ds;  
       gdImage.DataBind();  
     }  
     catch (Exception ex)  
     {  
       upload.Text = ex.Message;  
     }  
   }  
 }  


Monday, December 5, 2016

User Login in ASP.Net using C# with session


HTML Markup

The HTML markup consists of an ASP.Net Login control for which the OnAuthenticate event handler has been specified. <form id="form1" runat="server"> <asp:Login ID = "Login1" runat = "server" OnAuthenticate= "ValidateUser"></asp:Login> </form>

Namespaces

You will need to import the following namespaces. using System.Data; using System.Configuration; using System.Data.SqlClient; using System.Web.Security; Stored Procedure to Validate the User Credentials The following stored procedure is used to validate the user credentials, this stored procedure first checks whether the username and password are correct else returns -1. If the username and password are correct but the user has not been activated then the code returned is -2. If the username and password are correct and the user account has been activated then UserId of the user is returned by the stored procedure. CREATE PROCEDURE [dbo].[Validate_User] @Username NVARCHAR(20), @Password NVARCHAR(20) AS BEGIN SET NOCOUNT ON; DECLARE @UserId INT, @LastLoginDate DATETIME SELECT @UserId = UserId, @LastLoginDate = LastLoginDate FROM Users WHERE Username = @Username AND [Password] = @Password IF @UserId IS NOT NULL BEGIN IF NOT EXISTS(SELECT UserId FROM UserActivation WHERE UserId = @UserId) BEGIN UPDATE Users SET LastLoginDate = GETDATE() WHERE UserId = @UserId SELECT @UserId [UserId] -- User Valid END ELSE BEGIN SELECT -2 -- User not activated. END END ELSE BEGIN SELECT -1 -- User invalid. END END Validating the User Credentials The below event handler gets called when the Log In button is clicked. Here the Username and Password entered by the user is passed to the stored procedure and its status is captured and if the value is not -1 (Username or password incorrect) or -2 (Account not activated) then the user is redirected to the Home page using FormsAuthentication RedirectFromLoginPage method. protected void ValidateUser(object sender, EventArgs e) { int userId = 0; string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString; using (SqlConnection con = new SqlConnection(constr)) { using (SqlCommand cmd = new SqlCommand("Validate_User")) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@Username", Login1.UserName); cmd.Parameters.AddWithValue("@Password", Login1.Password); cmd.Connection = con; con.Open(); userId = Convert.ToInt32(cmd.ExecuteScalar()); con.Close(); } switch (userId) { case -1: Login1.FailureText = "Username and/or password is incorrect."; break; case -2: Login1.FailureText = "Account has not been activated."; break; default: FormsAuthentication.RedirectFromLoginPage(Login1.UserName, Login1.RememberMeSet); break; } } } Home Page After successful login user will be redirected to this page. HTML Markup In this page I have made use of ASP.Net LoginName control to display the name of the Logged In user and LoginStatus control to allow user Logout. <div> Welcome <asp:LoginName ID="LoginName1" runat="server" Font-Bold = "true" /> <br /> <br /> <asp:LoginStatus ID="LoginStatus1" runat="server" /> </div> Namespaces You will need to import the following namespaces. using System.Web.Security; Verify whether User has Logged In Inside the Page Load event, first we verify whether the User is authenticated using the IsAuthenticated property. If the user is not authenticated then he is redirected back to the Login page using FormsAuthentication RedirectToLoginPage method. protected void Page_Load(object sender, EventArgs e) { if (!this.Page.User.Identity.IsAuthenticated) { FormsAuthentication.RedirectToLoginPage(); } } Web.Config Configuration You will need to add the following configuration in the Web.Config file in the <system.web> section. <authentication mode="Forms"> <formsdefaultUrl="~/Home.aspx" loginUrl="~/Login.aspx" slidingExpiration="true" timeout="2880"></forms> </authentication>

LOGIN FORM USING C# & Sql Server

Login Credential from sqlserver database

 using System;   
 using System.Collections.Generic;   
 using System.ComponentModel;   
 using System.Data;   
 using System.Drawing;   
 using System.Linq;   
 using System.Text;   
 using System.Windows.Forms;   
 using System.Data.Sql;   
 using System.Data.OleDb;   
 using System.Data.SqlClient;   
 namespace login_form   
 {   
   public partial class Form1 : Form   
   {   
     SqlConnection con = new SqlConnection();   
     public Form1()   
     {   
       SqlConnection con = new SqlConnection();   
       con.ConnectionString = "Data Source=KRISHNA-PC\\SQLEXPRESS;Initial Catalog=STUDENT;Integrated Security=True";   
       InitializeComponent();   
     }   
     private void Form1_Load(object sender, EventArgs e)   
     {   
       
       SqlConnection con = new SqlConnection("Data Source=Home-PC\\SQLEXPRESS;Initial Catalog=STUDENT;Integrated Security=True");   
       con.Open();   
       {   
       }   
     }   
     private void button1_Click(object sender, EventArgs e)   
     {   
       SqlConnection con = new SqlConnection();   
       con.ConnectionString = "Data Source=Home-PC\\SQLEXPRESS;Initial Catalog=STUDENT;Integrated Security=True";   
       con.Open();   
       string userid = textBox1.Text;   
       string password = textBox2.Text;   
       SqlCommand cmd = new SqlCommand("select userid,password from login where userid='" + textBox1.Text + "'and password='" + text      Box2.Text + "'", con);   
       SqlDataAdapter da = new SqlDataAdapter(cmd);   
       DataTable dt = new DataTable();   
       da.Fill(dt);   
       if (dt.Rows.Count > 0)   
       {   
         MessageBox.Show("Login sucess Welcome to Homepage https://logicerrors.blogspot.in/");   
         System.Diagnostics.Process.Start("https://logicerrors.blogspot.in/");   
       }   
       else   
       {   
         MessageBox.Show("Invalid Login please check username and password");   
       }   
       con.Close();   
     }   
     private void button2_Click(object sender, EventArgs e)   
     {   
       Application.Exit();   
     }   
   }   
 }   

Monday, November 28, 2016

Download File From GridView Using ASP.Net



 <asp:FileUpload ID="FileUpload1" runat="server" />  
 <asp:Button ID="btnUpload" runat="server" Text="Upload" OnClick="UploadFile" />  
 <hr />  
 <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" EmptyDataText = "No files uploaded">  
   <Columns>  
     <asp:BoundField DataField="Text" HeaderText="File Name" />  
     <asp:TemplateField>  
       <ItemTemplate>  
         <asp:LinkButton ID="lnkDownload" Text = "Download" CommandArgument = '<%# Eval("Value") %>' runat="server" OnClick = "DownloadFile"></asp:LinkButton>  
       </ItemTemplate>  
     </asp:TemplateField>  
     <asp:TemplateField>  
       <ItemTemplate>  
         <asp:LinkButton ID = "lnkDelete" Text = "Delete" CommandArgument = '<%# Eval("Value") %>' runat = "server" OnClick = "DeleteFile" />  
       </ItemTemplate>  
     </asp:TemplateField>  
   </Columns>  
 </asp:GridView>  



Namespaces

You will need to import the following namespaces. C# using System.IO;


 Uploading the File and saving in directory or folder  
 When the file is selected in APS.Net FileUpload control and the Upload button is clicked the following event handler is triggered. Below I have folder Uploads in the root directory of my ASP.Net Website where I am saving the uploaded file.  
 C#  
 protected void UploadFile(object sender, EventArgs e)  
 {  
   string fileName = Path.GetFileName(FileUpload1.PostedFile.FileName);  
   FileUpload1.PostedFile.SaveAs(Server.MapPath("~/Uploads/") + fileName);  
   Response.Redirect(Request.Url.AbsoluteUri);  
 }  


 Displaying the files from folder or directory in ASP.Net GridView  
 Here I am reading all the files from the Uploads directory which I have created and then binding the fetched files to the ASP.Net GridView control.  
 C#  
 protected void Page_Load(object sender, EventArgs e)  
 {  
   if (!IsPostBack)  
   {  
     string[] filePaths = Directory.GetFiles(Server.MapPath("~/Uploads/"));  
     List<ListItem> files = new List<ListItem>();  
     foreach (string filePath in filePaths)  
     {  
       files.Add(new ListItem(Path.GetFileName(filePath), filePath));  
     }  
     GridView1.DataSource = files;  
     GridView1.DataBind();  
   }  
 }  


 Downloading the Uploaded File from ASP.Net GridView  
 The following event handler is executed when the lnkDownload LinkButton is clicked in the ASP.Net GridView Row. Using the CommandArgument property of the ASP.Net LinkButton, I get the path of the file using which I am downloading the file.  
 C#  
 protected void DownloadFile(object sender, EventArgs e)  
 {  
   string filePath = (sender as LinkButton).CommandArgument;  
   Response.ContentType = ContentType;  
   Response.AppendHeader("Content-Disposition", "attachment; filename=" + Path.GetFileName(filePath));  
   Response.WriteFile(filePath);  
   Response.End();  
 }  

Deleting the Uploaded File from ASP.Net GridView  
 The following event handler is executed when the lnkDelete LinkButton is clicked in the ASP.Net GridView Row. Using the CommandArgument property of the ASP.Net LinkButton, I get the path of the file using which I am deleting the file.  
 C#  
 
 protected void DeleteFile(object sender, EventArgs e)  
 {  
   string filePath = (sender as LinkButton).CommandArgument;  
   File.Delete(filePath);  
   Response.Redirect(Request.Url.AbsoluteUri);  
 }  

Wednesday, November 23, 2016

DropDownList Example in ASP.NET using C#

DropDownList Example in ASP.NET using C#

DropDownList.aspx (source code):

 <%@ Page Title="" Language="C#" MasterPageFile="~/RoseindiaMaster.master"  
 AutoEventWireup="true" CodeFile="DropDownList.aspx.cs" Inherits="DropDownList" %>  
 <asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">  
 <style type="text/css">  
 .style3  
 {  
 color: #800000;  
 }  
 </style>  
 </asp:Content>  
 <asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">  
 <div>  
 <h2 style="color:Green">DropDownList in ASP.NET 4 , C#</h2>  
 <strong><span class="style3">Enter first number:</span>  
 </strong>  
 <br />  
 <asp:TextBox ID="txt1" runat="server" Text="12"/>  
 <br />  
 <br />  
 <span class="style3">  
 <strong>Enter second number:  
 </strong>  
 </span>  
 <br />  
 <asp:TextBox ID="txt2" runat="server" Text="3" />  
 <br />  
 <br />  
 <span class="style3">  
 <strong>Select operation:  
 </strong>  
 </span>  
 <br />  
 <asp:DropDownList ID="drp1" runat="server" Width="145px"   
 Font-Bold="True" ForeColor="#006666"   
 onselectedindexchanged="drp1_SelectedIndexChanged" AutoPostBack="True">  
 <asp:ListItem>----Select----</asp:ListItem>  
 <asp:ListItem>Addition</asp:ListItem>  
 <asp:ListItem>Subtraction</asp:ListItem>  
 <asp:ListItem>Multiplication</asp:ListItem>  
 <asp:ListItem>Division</asp:ListItem>  
 </asp:DropDownList>  
 </div>  
 <br />  
 <asp:Label ID="label1" runat="server" Font-Bold="True" ForeColor="#000099" />  
 </asp:Content>  

DropDownList.aspx.cs (C# code file):

 using System;  
 using System.Collections.Generic;  
 using System.Linq;  
 using System.Web;  
 using System.Web.UI;  
 using System.Web.UI.WebControls;  
 public partial class DropDownList : System.Web.UI.Page  
 {  
 protected void Page_Load(object sender, EventArgs e)  
 {  
 }  
 protected void drp1_SelectedIndexChanged(object sender, EventArgs e)  
 {  
 double firstno = Convert.ToDouble(txt1.Text);  
 double secondno = Convert.ToDouble(txt2.Text);  
 if(drp1.SelectedIndex == 1)  
 {  
 double add = firstno + secondno;  
 label1.Text = "Addition is :" + add;  
 }  
 if (drp1.SelectedIndex == 2)  
 {  
 double sub = firstno - secondno;  
 label1.Text = "Subtraction is :" + sub;  
 }  
 if (drp1.SelectedIndex == 3)  
 {  
 double mul = firstno * secondno;  
 label1.Text = "Multiplication is :" + mul;  
 }  
 if (drp1.SelectedIndex == 4)  
 {  
 double div = firstno / secondno;  
 label1.Text = "Division is :" + div;  
 }  
 }  
 }  

OUTPUT


Tuesday, November 22, 2016

Dynamically change GridView Cell Background Color based on condition in ASP.Net using C#

The GridView Cell’s background color will be dynamically changed based on its value in the RowDataBound event of GridView.
GridView HTML Markup
The following HTML markup consists of an ASP.Net GridView consisting of two BoundField columns.


  <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" OnRowDataBound = "OnRowDataBound">
    <Columns>
        <asp:BoundField DataField="Item" HeaderText="Item" ItemStyle-Width = "100"/>
        <asp:BoundField DataField="Quantity" HeaderText="Quantity" ItemStyle-Width = "100"/>
    </Columns>
</asp:GridView>

Namespaces
You will need to import the following namespaces.
C#
using System.Data;
using System.Drawing;

Binding the ASP.Net GridView control
I have created a dynamic DataTable with some dummy data and it is used to populate the GridView control in the Page Load event.

 protected void Page_Load(object sender, EventArgs e)  
 {  
   if (!IsPostBack)  
   {  
     DataTable dt = new DataTable();  
     dt.Columns.AddRange(new DataColumn[2] { new DataColumn("Item"), new DataColumn("Quantity") });  
     dt.Rows.Add("Shirt", 145);  
     dt.Rows.Add("Jeans", 0);  
     dt.Rows.Add("Trousers", 190);  
     dt.Rows.Add("Tie", 30);  
     dt.Rows.Add("Cap", 0);  
     dt.Rows.Add("Hat", 90);  
     dt.Rows.Add("Scarf", 290);  
     dt.Rows.Add("Belt", 150);  
     GridView1.DataSource = dt;  
     GridView1.DataBind();  
   }  
 }  

Changing the Background color of GridView Row as per condition dynamically
Inside the OnRowDataBound event handler of the GridView, the Cell value is compared with different quantity ranges and based on the following quantity range values, the background color of the GridView Cell will change.
 protected void OnRowDataBound(object sender, GridViewRowEventArgs e)  
 {  
   if (e.Row.RowType == DataControlRowType.DataRow)  
   {  
     TableCell cell = e.Row.Cells[1];  
     int quantity = int.Parse(cell.Text);  
     if (quantity == 0)  
     {  
       cell.BackColor = Color.Red;  
     }  
     if (quantity > 0 && quantity <= 50)  
     {  
       cell.BackColor = Color.Yellow;  
     }  
     if (quantity > 50 && quantity <= 100)  
     {  
       cell.BackColor = Color.Orange;  
     }  
   }  
 }  


Insert, Update, Delete In GridView Using ASP.Net C#

Using Gridview & SIngle store Procedure Insert, Update, Delete In GridView with sql server



I have set the primary key on the id column and I have set the Identity specification to Yes.
Now we have a table to perform these operations for. Now let us start to create the Stored Procedure.
The Stored Procedure is created using the keyword "Create Procedure" followed by the procedure name. Let us create the Stored Prcedure named "EmpEntry" as in the following:

 create Procedure EmpEntry  
 (  
  --variable declareations   
  @Action Varchar (10),  --to perform operation according to string ed to this varible such as Insert,update,delete,select     
  @id int=null,  --id to perform specific task  
  @FnameVarchar (50)=null,  -- for FirstName  
  @MName Varchar (50)=null,  -- for MName  
  @Lname Varchar (50)=null  -- for LastName  
 )  
 as  
 Begin   
  SET NOCOUNT ON;  
 If @Action='Insert'  --used to insert records  
 Begin  
   Insert Into employee (FirstName,MName,LastName)values(@Fname,@MName,@Lname)  
 End   
 else if @Action='Select'  --used to Select records  
 Begin  
   select *from employee  
 end  
 else if @Action='Update' --used to update records  
 Begin  
   update employeeset FirstName=@Fname,MName=@MName,LastName=@Lname where id=@id  
  End  
  Else If @Action='delete' --used to delete records  
  Begin  
   delete from employeewhere id=@id  
  end  
  End  

The comments in the Stored Procedure above clearly explain which block is used for which purpose, so I have briefly explained it again. I have used the @Action variable and assigned the string to them and according to the parameter ed to the Stored Procedure the specific block will be executed because I have kept these blocks or conditions in nested if else if conditional statements.
"The most important thing is that I have assigned null to each variable to avoid the effect on the parameter ed to the Stored Procedure because we are ing a different number of parameters but not the same number of parameters to the Stored Procedure to perform these tasks."
Now create the one sample application "Empsys" as:
  1. "Start" - "All Programs" - "Microsoft Visual Studio 2010".
  2. "File" - "New Project" - "C#" - "Empty Web Application" (to avoid adding a master page).
  3. Provide the web site a name such as  "Empsys" or another as you wish and specify the location.
  4. Then right-click on Solution Explorer - "Add New Item" - "Default.aspx page".
  5. Drag and drop one button, three textboxes, one GridView and one hidden field to the hidden value to the database and one label on the 
     section of the Default.aspx page.
Then switch to the design view;
 <form id="form1"runat="server">  
   <div>  
 First Name <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>  
 Middle Name<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>  
 Last Name <asp:TextBox ID="TextBox3" runat="server"></asp:TextBox>  
     <asp:ButtonID="Button1"runat="server"Text="save"onclick="Button1_Click" />  
   </div>  
 <asp:HiddenField ID="HiddenField1" runat="server"/>  
  <asp:GridViewID="GridView1"runat="server" >  
    </asp:GridView>  
 </form>  

Now use the following GridView event properties to perform events such as update, delete, edit cancel and so on. Let us see what the properties are:
  • DataKeyNames: This property I have used to the the row index of GridView  
  • OnRowEditing: This property is used to handle the event when the user clicks on the edit button
  • OnRowCancelingEdit: This property is used to handle the event when the user clicks on the Cancel button that exists after clicking on the edit button
  • OnRowDeleting: This property is used to handle the event when the user clicks on the delete button that deletes the row of the GridView
  • OnRowUpdating: This property is used to handle the event when the user clicks on the update button that updates the Grid Record 
Now my grid will look such as the following:
   
  

On the preceding GridView properties I have assigned the method name to be called for particular operations.

 Method to Insert Data in Database   
 Right-click from the design page and view the code and then write the following code in the default.aspx.cs page to save the inserted records in the database:  
 protected void empsave(object sender, EventArgs e)  
 {  
    connection();  
    query = "studentEntryView";     //Stored Procedure name   
    SqlCommand com = new SqlCommand(query, con); //creating SqlCommand object  
    com.CommandType = CommandType.StoredProcedure; //here we declaring command type as stored Procedure  
     /* adding paramerters to SqlCommand below *\  
    com.Parameters.AddWithValue("@Action", HiddenField1.Value).ToString();//for ing hidden value to preform insert operation  
     com.Parameters.AddWithValue("@FName",TextBox1.Text.ToString());    //first Name  
     com.Parameters.AddWithValue("@Mname ", TextBox2.Text.ToString());   //middle Name  
     com.Parameters.AddWithValue("@LName ",TextBox3.Text.ToString());    //Last Name  
     com.ExecuteNonQuery();           //executing the sqlcommand  
     Label1.Visible = true;  
     Label1.Text = "Records are Submitted Successfully";  
 }  
 Now create the mehtod to view the records in the GridView:  
 public void viewdata()  
 {  
   connection();  
   query = "studentEntryView";  
   SqlCommand com = new SqlCommand(query, con);  
   com.CommandType = CommandType.StoredProcedure;  
   com.Parameters.AddWithValue("@Action", HiddenField2.Value).ToString();  
   DataSet ds =new DataSet();  
   SqlDataAdapter da = new SqlDataAdapter(com);  
   da.Fill(ds);  
   GridView1.DataSource = ds;  
   GridView1.DataBind();  
 }  
 The following is method for the "OnRowEditing" Event:  
 protected void edit(objectsender, GridViewEditEventArgs e)  
 {  
   GridView1.EditIndex= e.NewEditIndex;  
   gedata();  
 }  
 The following is method for the "OnRowCancelingEdit" Event:  
 protected void canceledit(object sender, GridViewCancelEditEventArgs e)  
 {  
   GridView1.EditIndex = -1;  
   gedata();  
 }  
 The following is method for the "OnRowDeleting" Event:  
 protected void delete(object sender, GridViewDeleteEventArgs e)  
 {  
    connection();  
    int id = int.Parse(GridView1.DataKeys[e.RowIndex].Value.ToString());  
    HiddenField1.Value = "Delete";  
    query = "EmpEntry";  
    com = new SqlCommand(query, con);  
    com.CommandType =CommandType .StoredProcedure;  
    com.Parameters.AddWithValue("@Action", HiddenField1.Value).ToString();  
    com.Parameters.AddWithValue("id", SqlDbType.Int).Value = id;  
    com.ExecuteNonQuery();  
    con.Close();  
    gedata();           
  }  
 The following is method for the "OnRowUpdating" Event:  
 protected void update(object sender, GridViewUpdateEventArgs e)  
 {  
    connection();  
    int id=int.Parse(GridView1.DataKeys[e.RowIndex].Value.ToString());  
    HiddenField1.Value = "update";  
    query = "EmpEntry";  
    com = new SqlCommand(query, con);  
    com.CommandType = CommandType.StoredProcedure;  
    com.Parameters.AddWithValue("@Action", HiddenField1.Value).ToString();  
    com.Parameters.AddWithValue("@FName", ((TextBox)GridView1.Rows[e.RowIndex].Cells[3].Controls[0]).Text.ToString());  
    com.Parameters.AddWithValue("@MName", ((TextBox)GridView1.Rows[e.RowIndex].Cells[4].Controls[0]).Text.ToString());  
    com.Parameters.AddWithValue("@LName", ((TextBox)GridView1.Rows[e.RowIndex].Cells[5].Controls[0]).Text.ToString());  
    com.Parameters.AddWithValue("@id", SqlDbType.int ).Value = id;  
    com.ExecuteNonQuery();  
    con.Close();  
    GridView1.EditIndex = -1;  
    gedata();  
 }  

Brief introduction to the codeIn the sample code above I have used the two string queries for giving the Stored Procedure name and the constr for storing the connection from the web.config file and another thing is that I have used a hidden field by which I am ing the action values that are required to our Stored Procedure.

Now our application is ready to use, press F5 or other as you know, then enter the some values to TextBox and press the "Save" button.


Now after clicking on the "Save" button, the hidden field value takes the value "Insert" and es it to the Stored Procedure as the action and because of this the Stored Procedure will execute a particular type of block.

Now at page load I have called the method, so after that the grid will fill as in:




Now click on the Edit button that calls the edit method as shown in the following grid:



If you click on the "Cancel" button then the editcancel method will be called and edit mode will be cancelled. Now enter some values into the grid TextBox and click on an update button that calls the update method and then the records in the GridView will be updated as in: