EmptyDataTemplate, EditItemTemplate and Others in a Gridview of ASP.Net

Requirements

  • We need to add data to the GridView row using the EmptyDatTemplate first.

  • Then we need to add data to the GridView using a FooterTemplate (because the EmptyDatTemplate is only visible when the GridView is blank and it can be used only one time, in a single operation).

  • The GridView also has the ability to edit, update, delete and cancel the operation.

  • Finally we need to send all the data of that GridView to the main table in the database.

  • After sending the data to the database, the GridView will be blank again.

I will be using a UserControl to develop this application as in the following:

  • Aspx Page Name: Empty_DataTemplate_Gridview_4.aspx.
  • UserControl Name: Gridview_EmptyDataTemplate_Control_4.ascx.

Procedure

  1. Database
  2. User Interface Design
  3. Program

SQL Server Database

  1. We need to use 2 Tables,
  2. One table as Temporary use,
  3. Another table for Permanent.

Database Table Structure

  1. use ASP_Complete_Practice  
  2. GO  
  3.   
  4. -- Table structure for Temporary use  
  5.   
  6. create table tbl_Temp_Gridview4  
  7. (  
  8. ID int identity primary key,  
  9. Name varchar(50),  
  10. Mobile bigint,  
  11. EmailID varchar(100),  
  12. Address varchar(100)  
  13. )  
  14.   
  15.   
  16. --- Table for Permanent Use  
  17.   
  18. create table tbl_Gridview4  
  19. (  
  20. Regid varchar(50),  
  21. ID int identity primary key,   
  22. Name varchar(50),  
  23. Mobile bigint,  
  24. EmailID varchar(100),  
  25. Address varchar(100)  

Design Of The Application Form

Design Of The Application Form

How to Design the Form

1. Drag a GridView and design it.

2. Select and click on Auto Format from the GridView tasks.

Select and Click on Auto Format

3. Select a Scheme from the left side such as Professional and click Apply and OK.

Click Apply and OK

4. Click on Edit Column on the GridView Task.

Edit Column on the Gridview Task

5. Add some bound fields to the GridView.

Add Some Bound Fields

6. Add a property to the bound fields such as Header Field, Data Field name and then convert the bound fields to the Template Fields.

Add Property to the bound

7. Uncheck the CheckBox from the left side (Auto-generate fields).

CheckBox

8. Add an Extra Template Field to the GridView and name it Add New and click on OK.

Add a Extra Template

9. Click on Edit Templates from GridView Tasks.

 Edit Templates from Gridview Task

10. Select a template from the GridView Tasks and design it.

Task and Design
11. Add a TextBox to the Footer Template.

Footer Template

12. Add a TextBox to all the templates like this except the Add New Template.

Except the Add New Template

13. Add a button to the FooterTemplate of the Add new Template.

FooterTemplate

14. Add a property to the button at the Add New Template, remember here the CommandName property is very important.

remember the CommandName

15. Add a new template to the GridView and give it a name.

Add a new Template

16. Add a TemplateField and provide an Edit / Delete name to the Header text.

TemplateField
17. Add two buttons to the ItemTemplate and two buttons to the EditItemTemplate of this new template (Edit / Delete Template).

new Template

18. Add a CommandName as Edit to the GridView Edit button.

Edit button

19. Add a CommandName as Delete to the GridView Delete button.

Delete button

20. Add a CommanName as Update to the GridView Update Button.
Update Button

21. Add a CommandName as Cancel to the GridView Cancel Button.

Add CommandName

22. Click on End Template Editing at the GridView Task.

Gridview Task
23. Select GridView Property by right-clicking on the GridView.

Right Clicking on the Gridview

24. Set this property as ShowFooter to True, ShowHeaderWhenEmpty to True.

ShowHeaderWhenEmpty

Design the GridView for EmptyDataTemplate

25. Click again on the Edit Template at the GridView Tasks.

Edit Template

26. Select EmptyDataTemplate from the GridView Tasks.

EmptyDataTemplate

27. Add 4 TextBoxes and 1 button to the EmptyDataTemplate.

Button

28. Provide the property to the Button at the EmptyDatatEmplate such as the CommandName as AddNew1, (Remember here the CommandName is very Important) ID as btnAddGrid1 name and others.

Property to the Button
Complete Design of the GridView Until Now (Source View)

  1. <asp:GridView ID="GridView1" runat="server" CellPadding="4" ForeColor="#333333"   
  2.      GridLines="None" AutoGenerateColumns="False" ShowFooter="True"   
  3.      ShowHeaderWhenEmpty="True" onrowcommand="GridView1_RowCommand"   
  4.      AllowPaging="True" DataKeyNames="ID"   
  5.      onpageindexchanging="GridView1_PageIndexChanging"   
  6.      onrowdeleting="GridView1_RowDeleting" PageSize="4" Width="873px"   
  7.      onrowediting="GridView1_RowEditing"   
  8.      onrowcancelingedit="GridView1_RowCancelingEdit"   
  9.      onrowupdating="GridView1_RowUpdating">  
  10.      <AlternatingRowStyle BackColor="White" ForeColor="#284775" />  
  11.      <Columns>  
  12.          <asp:TemplateField HeaderText="ID">  
  13.              <%--<EditItemTemplate>  
  14.                  <asp:TextBox ID="TextBox5" runat="server" Text='<%# Bind("ID") %>'></asp:TextBox>  
  15.              </EditItemTemplate>--%>  
  16.              <ItemTemplate>  
  17.                  <asp:Label ID="Label5" runat="server" Text='<%# Bind("ID") %>'></asp:Label>  
  18.              </ItemTemplate>  
  19.          </asp:TemplateField>  
  20.          <asp:TemplateField HeaderText="Name">  
  21.              <EditItemTemplate>  
  22.                  <asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("Name") %>'></asp:TextBox>  
  23.              </EditItemTemplate>  
  24.              <FooterTemplate>  
  25.                  <asp:TextBox ID="TextBox5" runat="server" CssClass="SmallTextBox"></asp:TextBox>  
  26.              </FooterTemplate>  
  27.              <ItemTemplate>  
  28.                  <asp:Label ID="Label1" runat="server" Text='<%# Bind("Name") %>'></asp:Label>  
  29.              </ItemTemplate>  
  30.              <ControlStyle Width="100px" />  
  31.              <FooterStyle Width="100px" />  
  32.              <HeaderStyle Width="100px" />  
  33.              <ItemStyle Width="100px" />  
  34.          </asp:TemplateField>  
  35.          <asp:TemplateField HeaderText="Mobile">  
  36.              <EditItemTemplate>  
  37.                  <asp:TextBox ID="TextBox2" runat="server" Text='<%# Bind("Mobile") %>'></asp:TextBox>  
  38.              </EditItemTemplate>  
  39.              <FooterTemplate>  
  40.                  <asp:TextBox ID="TextBox6" runat="server" CssClass="SmallTextBox"></asp:TextBox>  
  41.              </FooterTemplate>  
  42.              <ItemTemplate>  
  43.                  <asp:Label ID="Label2" runat="server" Text='<%# Bind("Mobile") %>'></asp:Label>  
  44.              </ItemTemplate>  
  45.              <ControlStyle Width="100px" />  
  46.              <FooterStyle Width="100px" />  
  47.              <HeaderStyle Width="100px" />  
  48.              <ItemStyle Width="100px" />  
  49.          </asp:TemplateField>  
  50.          <asp:TemplateField HeaderText="EmailID">  
  51.              <EditItemTemplate>  
  52.                  <asp:TextBox ID="TextBox3" runat="server" Text='<%# Bind("EmailID") %>'></asp:TextBox>  
  53.              </EditItemTemplate>  
  54.              <FooterTemplate>  
  55.                  <asp:TextBox ID="TextBox7" runat="server" Width="170px"></asp:TextBox>  
  56.              </FooterTemplate>  
  57.              <ItemTemplate>  
  58.                  <asp:Label ID="Label3" runat="server" Text='<%# Bind("EmailID") %>'></asp:Label>  
  59.              </ItemTemplate>  
  60.              <ControlStyle Width="180px" />  
  61.              <FooterStyle Width="180px" />  
  62.              <HeaderStyle Width="180px" />  
  63.              <ItemStyle Width="180px" />  
  64.          </asp:TemplateField>  
  65.          <asp:TemplateField HeaderText="Address">  
  66.              <EditItemTemplate>  
  67.                  <asp:TextBox ID="TextBox4" runat="server" Text='<%# Bind("Address") %>'></asp:TextBox>  
  68.              </EditItemTemplate>  
  69.              <FooterTemplate>  
  70.                  <asp:TextBox ID="TextBox8" runat="server" CssClass="SmallTextBox" Width="150px"></asp:TextBox>  
  71.              </FooterTemplate>  
  72.              <ItemTemplate>  
  73.                  <asp:Label ID="Label4" runat="server" Text='<%# Bind("Address") %>'></asp:Label>  
  74.              </ItemTemplate>  
  75.              <ControlStyle Width="150px" />  
  76.              <FooterStyle Width="150px" />  
  77.              <HeaderStyle Width="150px" />  
  78.              <ItemStyle Width="150px" />  
  79.          </asp:TemplateField>  
  80.          <asp:TemplateField HeaderText="Add New">  
  81.              <FooterTemplate>  
  82.                  <asp:Button ID="btnAddGrid2" runat="server" CommandName="AddNew2"   
  83.                      CssClass="SmallButton" Text="Add" />  
  84.              </FooterTemplate>  
  85.              <ControlStyle Width="70px" />  
  86.              <FooterStyle Width="70px" />  
  87.              <HeaderStyle Width="70px" />  
  88.              <ItemStyle Width="70px" />  
  89.          </asp:TemplateField>  
  90.          <asp:TemplateField HeaderText="Edit / Delete ">  
  91.              <EditItemTemplate>  
  92.                  <asp:Button ID="btnGridUpdate" runat="server" CssClass="SmallButton"   
  93.                      Text="Update" CommandName="Update" />  
  94.                  <asp:Button ID="btnGridCancel" runat="server" CssClass="SmallButton"   
  95.                      Text="Cancel" CommandName="Cancel" />  
  96.              </EditItemTemplate>  
  97.              <ItemTemplate>  
  98.                  <asp:Button ID="btnGridEdit" runat="server" CssClass="SmallButton"   
  99.                      Text="Edit" CommandName="Edit" />  
  100.                  <asp:Button ID="btnGridDelete" runat="server" CssClass="SmallButton"   
  101.                      Text="Delete" CommandName="Delete" OnClientClick="return confirm('Are You Sure You Want To Delete ?')" />  
  102.              </ItemTemplate>  
  103.              <HeaderStyle Width="130px" />  
  104.          </asp:TemplateField>  
  105.      </Columns>  
  106.      <EditRowStyle BackColor="#999999" />  
  107.      <EmptyDataTemplate>  
  108.          <asp:TextBox ID="TextBox9" runat="server" CssClass="SmallTextBox"></asp:TextBox>  
  109.          <asp:TextBox ID="TextBox10" runat="server" CssClass="SmallTextBox"></asp:TextBox>  
  110.          <asp:TextBox ID="TextBox11" runat="server" CssClass="SmallTextBox"   
  111.              Width="170px"></asp:TextBox>  
  112.          <asp:TextBox ID="TextBox12" runat="server" CssClass="SmallTextBox"   
  113.              Width="150px"></asp:TextBox>  
  114.          <asp:Button ID="btnAddGrid1" runat="server" CommandName="AddNew1"   
  115.              CssClass="SmallButton" Text="Add New" />  
  116.      </EmptyDataTemplate>  
  117.      <FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />  
  118.      <HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />  
  119.      <PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />  
  120.      <RowStyle BackColor="#F7F6F3" ForeColor="#333333" />  
  121.      <SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />  
  122.      <SortedAscendingCellStyle BackColor="#E9E7E2" />  
  123.      <SortedAscendingHeaderStyle BackColor="#506C8C" />  
  124.      <SortedDescendingCellStyle BackColor="#FFFDF8" />  
  125.      <SortedDescendingHeaderStyle BackColor="#6F8DAE" />  
  126.  </asp:GridView> 

Programming Starts Here

Place the following code in the Gridview_EmptyDataTemplate_Control_4.ascx.cs file.

29. Add these namespaces:

  1. using System.Data;  
  2. using System.Data.SqlClient;  
  3. using System.Drawing;  
  4. using System.Configuration; 

30. The following are the database connection and some variable declarations.

  1. public partial class Tech_Test_Controls_Gridview_Control_4 : System.Web.UI.UserControl  
  2. {  
  3.   
  4.     SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["CONN"].ConnectionString.ToString());  
  5.   
  6. //  
  7.     int i;  
  8.   
  9.     // declar Five variables here  
  10.     int ID;  
  11.     string Name, EmailID, Address;  
  12.     long Mobile;  
  13.     //  
  14.     DataTable Dt = new DataTable();  
  15.   
  16.   

31. First of all, we need to check if the Registration Number already exists or not.

Click on the TextBox or in the TextChangedEvent of the TextBox for the Registration Number.

Registration Number

  1. protected void txtRegidtNo_TextChanged(object sender, EventArgs e)  
  2. {  
  3.     // this method is used to check if the Registration number already exist or not  
  4.     CheckRegistrationNo();  
  5. }  
  6.   
  7. private void CheckRegistrationNo()  
  8. {  
  9.     // this method is used to check if the Registration number already exist or not  
  10.   
  11.     try  
  12.     {  
  13.         string Query = "select Regid from tbl_Gridview4 where Regid=@Regid";  
  14.         //  
  15.         SqlCommand cmd = new SqlCommand(Query, con);  
  16.         cmd.Parameters.AddWithValue("@Regid", txtRegidtNo.Text);  
  17.         con.Open();  
  18.         SqlDataReader dr = cmd.ExecuteReader();  
  19.         if (dr.Read())  
  20.         {  
  21.             lblMessage1.Visible = true;  
  22.             lblMessage1.ForeColor = Color.Red;  
  23.             lblMessage1.Text = "This Registration Number is Already Exist, Please try Another ...";  
  24.             //  
  25.             dr.Close();  
  26.             con.Close();  
  27.         }  
  28.         else  
  29.         {  
  30.             dr.Close();  
  31.             con.Close();  
  32.             //  
  33.             lblMessage1.Visible = false;  
  34.         }  
  35.          
  36.   
  37.     }  
  38.     catch (Exception Exc)  
  39.     {  
  40.         lblMessage1.Visible = true;  
  41.         lblMessage2.ForeColor = Color.Red;  
  42.         lblMessage1.Text = " Application Error :  " + Exc.Message;  
  43.     }  
  44.   
  45.     finally  
  46.     {  
  47.         //  
  48.     }  

32. Retrieving the data from the temporary table to load the GridView.

  1. protected void Page_Load(object sender, EventArgs e)  
  2. {  
  3.     if (!IsPostBack)  
  4.     {  
  5.         //Loading the Gridview  
  6.         LoadGridView();  
  7.     }  
  8. }  
  9.   
  10. private void LoadGridView()  
  11. {  
  12.     // This Method will load the Gridview with Initial Data from the Temporary Table  
  13.     try  
  14.     {  
  15.         string Query = "select * from tbl_Temp_Gridview4";  
  16.         //  
  17.         SqlCommand cmd = new SqlCommand(Query, con);  
  18.         SqlDataAdapter da = new SqlDataAdapter();  
  19.         da.SelectCommand = cmd;  
  20.         //  
  21.         con.Open();  
  22.         da.Fill(Dt);  
  23.         con.Close();  
  24.         //  
  25.         GridView1.DataSource = Dt;  
  26.         GridView1.DataBind();  
  27.     }  
  28.     catch (Exception Exc)  
  29.     {  
  30.         lblMessage2.Visible = true;  
  31.         lblMessage2.ForeColor = Color.Red;  
  32.         lblMessage2.Text = " Application Error :  " + Exc.Message;  
  33.     }  
  34.   
  35.     finally  
  36.     {  
  37.         //  
  38.     }  

33. Run the project and watch the output.

Run the Project

34. Inserting the data with the EmptyDataTemplate.

35. Select GridvView, right-click and select Property, then select Event and click on the GridviewRowCommand event.

GridviewRowCommand Event

  1. protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)  
  2. {  
  3.     try  
  4.     {  
  5.         if (txtRegidtNo.Text == "")  
  6.         {  
  7.             lblMessage1.Visible = true;  
  8.             lblMessage1.ForeColor = Color.Red;  
  9.             lblMessage1.Text = "Please Enter The Registration Number First";  
  10.         }  
  11.         else  
  12.         {  
  13.             lblMessage1.Visible = false;  
  14.             //  
  15.             //check registration number  
  16.             CheckRegistrationNo();  
  17.   
  18.             GridViewRow row = (GridViewRow)(e.CommandSource as Button).NamingContainer;  
  19.   
  20.             // this method will call first when the Gridview is Empty and the EmptyDataTemplate is Called here  
  21.   
  22.             if (e.CommandName == "AddNew1")  
  23.             {  
  24.                 // finding the value from the TextBox inside the EmptyDataTempalte  
  25.                 Name = (row.FindControl("TextBox9"as TextBox).Text;  
  26.                 Mobile = Convert.ToInt64((row.FindControl("TextBox10"as TextBox).Text);  
  27.                 EmailID = (row.FindControl("TextBox11"as TextBox).Text;  
  28.                 Address = (row.FindControl("TextBox12"as TextBox).Text;  
  29.                 //  
  30.                 string Query = "insert into tbl_Temp_Gridview4 (Name,Mobile,EmailID,Address) values(@Name,@Mobile,@EmailID,@Address)";  
  31.                 //  
  32.                 SqlCommand cmd = new SqlCommand(Query, con);  
  33.                 //  
  34.                 cmd.Parameters.AddWithValue("@Name", Name);  
  35.   
  36.                 cmd.Parameters.AddWithValue("@Mobile", Mobile);  
  37.   
  38.                 cmd.Parameters.AddWithValue("@EmailID", EmailID);  
  39.   
  40.                 cmd.Parameters.AddWithValue("@Address", Address);  
  41.                 //  
  42.                 con.Open();  
  43.                 i = cmd.ExecuteNonQuery();  
  44.                 con.Close();  
  45.                 //  
  46.                 if (i > 0)  
  47.                 {  
  48.                     //loading the Gridview  
  49.                     LoadGridView();  
  50.                     //  
  51.                     lblMessage2.Visible = true;  
  52.                     lblMessage2.ForeColor = Color.Green;  
  53.                     lblMessage2.Text = "One Record Add Sucessfully";  
  54.                 }  
  55.             }  
  56.   
  57.             // this method will called in FooterTemplate after one record is added to the Gridview  
  58.   
  59.             if (e.CommandName == "AddNew2")  
  60.             {  
  61.                 // finding the value from the TextBox inside the EmptyDataTempalte  
  62.                 Name = (row.FindControl("TextBox5"as TextBox).Text;  
  63.                 Mobile = Convert.ToInt64((row.FindControl("TextBox6"as TextBox).Text);  
  64.                 EmailID = (row.FindControl("TextBox7"as TextBox).Text;  
  65.                 Address = (row.FindControl("TextBox8"as TextBox).Text;  
  66.                 //  
  67.                 string Query = "insert into tbl_Temp_Gridview4 (Name,Mobile,EmailID,Address) values(@Name,@Mobile,@EmailID,@Address)";  
  68.                 //  
  69.                 SqlCommand cmd = new SqlCommand(Query, con);  
  70.                 //  
  71.                 cmd.Parameters.AddWithValue("@Name", Name);  
  72.   
  73.                 cmd.Parameters.AddWithValue("@Mobile", Mobile);  
  74.   
  75.                 cmd.Parameters.AddWithValue("@EmailID", EmailID);  
  76.   
  77.                 cmd.Parameters.AddWithValue("@Address", Address);  
  78.                 //  
  79.                 con.Open();  
  80.                 i = cmd.ExecuteNonQuery();  
  81.                 con.Close();  
  82.                 //  
  83.                 if (i > 0)  
  84.                 {  
  85.                     //loading the Gridview  
  86.                     LoadGridView();  
  87.                     //  
  88.                     lblMessage2.Visible = true;  
  89.                     lblMessage2.ForeColor = Color.Green;  
  90.                     lblMessage2.Text = "One Record Add Sucessfully";  
  91.                 }  
  92.   
  93.             }  
  94.         }  
  95.   
  96.     }  
  97.     catch (Exception Exc)  
  98.     {  
  99.         lblMessage2.Visible = true;  
  100.         lblMessage2.ForeColor = Color.Red;  
  101.         lblMessage2.Text = " Application Error :  " + Exc.Message;  
  102.     }  
  103.   
  104.     finally  
  105.     {  
  106.         //  
  107.     }  

36. Run the application and here is the output.

Output

37. If the GridView is exceeding the page, then set it's a Column property.

38. Go to GridView, right-click on Edit Columns.

Edit Columns

39. As an example.

Example

40. Display the output after changing the width.

output after changing the Width

41. Click on the GridviewPageIndexChanging event.

GridviewPageIndexChanging

  1. protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)  
  2. {  
  3.    // Doing Paging here  
  4.    GridView1.PageIndex = e.NewPageIndex;  
  5.   
  6.    //Calling tne Function to load the Gridview 
  7.    LoadGridView();  

42. Set the GridView Property Allow Paging to True and PageSize to 4.

True and PageSize

43. Run the application and display the output.

Run The Application and watch the Output

44. Deleting the rows from the GridView.

45. Before that provide the DataKeyNames to the GridView as ID.

DataKeyNames

Provide the code in the Source View of the GridView for Confirmation Message (OnClientClick="return confirm('Are You Sure You Want To Delete ?')").

  1. <ItemTemplate>  
  2.    <asp:Button ID="btnGridDelete" runat="server" CssClass="SmallButton"  
  3.    Text="Delete" CommandName="Delete" OnClientClick="return confirm('Are You Sure You Want To Delete ?')" />  
  4. </ItemTemplate> 

46. Select GridView RowDeleting event.

Select Gridview

47. Provide the following code in the GridView RowDeleting event.

  1. protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)  
  2. {  
  3.     if (con.State == ConnectionState.Open)  
  4.     {  
  5.         con.Close();  
  6.     }  
  7.   
  8.     try  
  9.     {  
  10.         //retrieving the DataKey name here  
  11.         ID = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Value.ToString());  
  12.   
  13.         string Query = "delete from tbl_Temp_Gridview4 where ID=@ID";  
  14.         //  
  15.         SqlCommand cmd = new SqlCommand(Query, con);  
  16.         cmd.Parameters.AddWithValue("@ID", ID);  
  17.         //  
  18.         con.Open();  
  19.         i = cmd.ExecuteNonQuery();  
  20.         if (i > 0)  
  21.         {  
  22.             //Load the Gridview  
  23.             LoadGridView();  
  24.         }  
  25.         con.Close();  
  26.   
  27.     }  
  28.     catch (Exception Exc)  
  29.     {  
  30.         lblMessage2.Visible = true;  
  31.         lblMessage2.ForeColor = Color.Red;  
  32.         lblMessage2.Text = " Application Error :  " + Exc.Message;  
  33.     }  
  34.   
  35.     finally  
  36.     {  
  37.         //  
  38.     }  

48. Run the application and try to delete a row from the GridView.

Row from the Gridview

49. Edit and update The GridView row.

50. Click on the RowEditing event of the GridView.

RowEditing Event
51. Provide the code here:

  1. protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)  
  2. {  
  3.    //this line of code will open the Gridview in the Edit mode  
  4.    GridView1.EditIndex = e.NewEditIndex;  

52. Cancelling the edit.

53. Click on the RowCancelingEdit event.

RowCancelingEdit
54. Provide the code.

  1. protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)  
  2. {  
  3.    //this code will Cancel the row edit  
  4.    GridView1.EditIndex = -1;  
  5.   
  6.    //Loading the Gridview again 
  7.    LoadGridView();  

55. Run the application and dispaly the output after the Cancel Event has been handled.

Run the application

56. Updating the GridView row.

Gridview row

57. Provide the following code.

  1. protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)  
  2. {  
  3.     try  
  4.     {  
  5.         //retrieving the DataKey name here  
  6.         ID = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Value.ToString());  
  7.   
  8.         // ((TextBox)GridView1.Rows[e.RowIndex].FindControl("TextBox2")).Text;  
  9.   
  10.         Name = (GridView1.Rows[e.RowIndex].FindControl("TextBox1"as TextBox).Text;  
  11.         Mobile = Convert.ToInt64((GridView1.Rows[e.RowIndex].FindControl("TextBox2"as TextBox).Text);  
  12.         EmailID = (GridView1.Rows[e.RowIndex].FindControl("TextBox3"as TextBox).Text;  
  13.         Address = (GridView1.Rows[e.RowIndex].FindControl("TextBox4"as TextBox).Text;  
  14.   
  15.         string Query = "update tbl_Temp_Gridview4 set Name=@Name, Mobile=@Mobile, EmailID=@EmailID, Address=@Address where ID=@ID ";  
  16.         //  
  17.         SqlCommand cmd = new SqlCommand(Query, con);  
  18.         //  
  19.         cmd.Parameters.AddWithValue("@Name", Name);  
  20.   
  21.         cmd.Parameters.AddWithValue("@Mobile", Mobile);  
  22.   
  23.         cmd.Parameters.AddWithValue("@EmailID", EmailID);  
  24.   
  25.         cmd.Parameters.AddWithValue("@Address", Address);  
  26.   
  27.         cmd.Parameters.AddWithValue("@ID", ID);  
  28.         //  
  29.         con.Open();  
  30.         i = cmd.ExecuteNonQuery();  
  31.         con.Close();  
  32.         //  
  33.         if (i > 0)  
  34.         {  
  35.               
  36.             // Closing the Editmode  
  37.             GridView1.EditIndex = -1;  
  38.             //  
  39.   
  40.             //loading the Gridview  
  41.             LoadGridView();  
  42.             //  
  43.   
  44.             lblMessage2.Visible = true;  
  45.             lblMessage2.ForeColor = Color.Green;  
  46.             lblMessage2.Text = "One Record Updated Sucessfully";  
  47.         }  
  48.   
  49.     }  
  50.     catch (Exception Exc)  
  51.     {  
  52.         lblMessage2.Visible = true;  
  53.         lblMessage2.ForeColor = Color.Red;  
  54.         lblMessage2.Text = " Application Error :  " + Exc.Message;  
  55.     }  
  56.   
  57.     finally  
  58.     {  
  59.         //  
  60.     }  
  61.      

58. Then save all this GridView data along with Registration number to the permanent table.

59. Click on the Save All button at the form.

Click on the Save

60. Before that, add validation to the TextBox, so that it will not be empty and provide the Validation Group to the Save All Button.

  1. <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server"  
  2. ControlToValidate="txtRegidtNo" ErrorMessage="* Enter Registration Number"  
  3. ForeColor="Red" ValidationGroup="abc">* Enter Registration Number</asp:RequiredFieldValidator> 

61. After clicking on the Save All Button, if the TextBox is Empty, you will get an error as in the following.

Clicking on the Sava All Button

62. After completing the validation, provide the code to save all the GridView data to the database.

63. After saving all the GridView data to the database permanent table, delete all the data from the first or temporary table.

64. Click on the Save All Button and write this code.

  1. protected void btnSaveAll_Click(object sender, EventArgs e)  
  2. {  
  3.     // fanally saving all data to the Main table in the database  
  4.     try  
  5.     {  
  6.         string RgNo;  
  7.         //  
  8.         if (con.State == ConnectionState.Open)  
  9.         {  
  10.             con.Close();  
  11.         }  
  12.         if (txtRegidtNo.Text != "")  
  13.         {  
  14.             RgNo = txtRegidtNo.Text;  
  15.   
  16.             // this will find all the dat from the Gridview row  
  17.             foreach (GridViewRow row in GridView1.Rows)  
  18.             {  
  19.                 Name = (row.FindControl("Label1"as Label).Text;  
  20.                 Mobile = Convert.ToInt64((row.FindControl("Label2"as Label).Text);  
  21.                 EmailID = (row.FindControl("Label3"as Label).Text;  
  22.                 Address = (row.FindControl("Label4"as Label).Text;  
  23.                 //  
  24.   
  25.                 string Query = "insert into tbl_Gridview4 (Regid,Name,Mobile,EmailID,Address) values(@Regid,@Name,@Mobile,@EmailID,@Address)";  
  26.                 //  
  27.                 SqlCommand cmd = new SqlCommand(Query, con);  
  28.                 //  
  29.                 cmd.Parameters.AddWithValue("@Regid", RgNo);  
  30.   
  31.                 cmd.Parameters.AddWithValue("@Name", Name);  
  32.   
  33.                 cmd.Parameters.AddWithValue("@Mobile", Mobile);  
  34.   
  35.                 cmd.Parameters.AddWithValue("@EmailID", EmailID);  
  36.   
  37.                 cmd.Parameters.AddWithValue("@Address", Address);  
  38.                 //  
  39.                 con.Open();  
  40.                 i = cmd.ExecuteNonQuery();  
  41.                 con.Close();  
  42.                 //  
  43.                 if (i > 0)  
  44.                 {  
  45.                     //once all data is saved, data from the temporary table need to deleted  
  46.                     if (con.State == ConnectionState.Open)  
  47.                     {  
  48.                         con.Close();  
  49.                     }  
  50.   
  51.                     string Query2 = "truncate table tbl_Temp_Gridview4 ";  
  52.                     //  
  53.                     SqlCommand cmd2 = new SqlCommand(Query2, con);  
  54.                     //  
  55.                     con.Open();  
  56.                     int B = cmd2.ExecuteNonQuery();  
  57.                     con.Close();  
  58.   
  59.                     //  
  60.                     //  
  61.                     lblMessage2.Visible = true;  
  62.                     lblMessage2.ForeColor = Color.Green;  
  63.                     lblMessage2.Text = "All Data Saved Sucessfully";  
  64.   
  65.                     //Loading the gridview again  
  66.                     LoadGridView();  
  67.   
  68.                     //clearing the Gridview  
  69.                     txtRegidtNo.Text = "";  
  70.   
  71.                 }  
  72.             }  
  73.         }   
  74.     }  
  75.     catch (Exception Exc)  
  76.     {  
  77.         lblMessage2.Visible = true;  
  78.         lblMessage2.ForeColor = Color.Red;  
  79.         lblMessage2.Text = " Application Error :  " + Exc.Message;  
  80.     }  
  81.   
  82.     finally  
  83.     {  
  84.         //  
  85.     }    

65. Watch the output again.

Watch The Output

I am using the complete source of the design here again.

  1. <%@ Control Language="C#" AutoEventWireup="true" CodeFile="Gridview_EmptyDataTemplate_Control_4.ascx.cs" Inherits="Tech_Test_Controls_Gridview_Control_4" %>  
  2.      <style type="text/css">  
  3.          
  4.         .Clear  
  5.         {  
  6.             clear:both;  
  7.         }  
  8.           
  9.         .logButton  
  10.         {  
  11.           width: 100px;  
  12.           height: 30px;  
  13.           background-color: #FB5F67;  
  14.           font-family: Arial, Helvetica, sans-serif; font-size: 13px; font-weight: bold; font-style: normal;   
  15.             font-variant: normal; text-transform: capitalize; color: #FFFFFF;       
  16.         }  
  17.         a:hover {color:#FF00FF;}  
  18.         a:link    {color:blue;}  
  19.         a:visited {color:green;}  
  20.         a:active  {color:yellow;}  
  21.           
  22.         input[type="submit"]:hover {  
  23.     background:#0000FF;  
  24. }  
  25.   
  26.         .LoginBox  
  27.         {  
  28.             margin: 10px;  
  29.             height: 270px;  
  30.             background-color: #FB5F67;  
  31.         }  
  32.         .Heading  
  33.         {  
  34.             margin: 10px;  
  35.             height: 15px;  
  36.             background-color: #FFFFFF;  
  37.             font-family: Arial, Helvetica, sans-serif; font-size: 12px; font-weight: bold; font-style: normal;   
  38.             font-variant: normal; text-transform: capitalize; color: #6C6B6B;   
  39.             text-align: center;  
  40.             padding: 4px;  
  41.         }  
  42.   
  43.         .InnerLogin  
  44.         {  
  45.             margin: 10px;  
  46.             margin-right: 5px;  
  47.             width: 320px;  
  48.             height: 250px;  
  49.             float: left;  
  50.             background-color: White;  
  51.         }  
  52.         .NewUserBox  
  53.         {  
  54.             margin: 10px;  
  55.             margin-left: 5px;          
  56.             width: 330px;  
  57.             height: 250px;  
  58.             float: left;  
  59.             background-color: White;  
  60.         }  
  61.   
  62.         .ClickButton  
  63.         {  
  64.           width: 100px;  
  65.           height: 30px;  
  66.           background-color: #339933;  
  67.           font-family: Arial, Helvetica, sans-serif; font-size: 13px; font-weight: bold; font-style: normal;   
  68.           font-variant: normal; text-transform: capitalize; color: #FFFFFF;       
  69.         }  
  70.                  
  71.          .ContentInside  
  72.          {  
  73.              margin: 10px;  
  74.          }  
  75.           
  76.      .TextBoxSize  
  77.          {  
  78.              width: 200px;  
  79.          }  
  80.   
  81.      .SmallTextBox  
  82.          {  
  83.             width: 100px;    
  84.          }  
  85.            
  86.          .DropDownSize  
  87.          {  
  88.            width: 255px;  
  89.            height: 23px;    
  90.          }  
  91.      .ContentMiddle  
  92.          {  
  93.              margin: 0px auto;  
  94.              height: auto;  
  95.              width: 500px;  
  96.          }  
  97.           
  98.          .LeftHeading  
  99.          {  
  100.              font-family: Arial, Helvetica, sans-serif;  
  101.              font-size: 14px;  
  102.              font-weight: bold;  
  103.              font-style: normal;  
  104.              font-variant: normal;  
  105.              text-transform: capitalize;  
  106.              color: #CC3300;  
  107.              text-align: left;  
  108.          }  
  109.   
  110.      .SubHeadingLeft  
  111.          {  
  112.              margin: 10px;  
  113.              height: 15px;  
  114.              padding: 4px;  
  115.              background-color: #999999;  
  116.              font-family: Arial, Helvetica, sans-serif;  
  117.              font-size: 12px;  
  118.              font-weight: bold;  
  119.              font-style: normal;  
  120.              font-variant: normal;  
  121.              text-transform: capitalize;  
  122.              color: #FFFFFF;  
  123.              text-align: left;  
  124.          }  
  125.   
  126.     .SmallButton  
  127.         {  
  128.           width: 60px;  
  129.           height: 30px;  
  130.           background-color: #666633;  
  131.           font-family: Arial, Helvetica, sans-serif; font-size: 13px; font-weight: bold; font-style: normal;   
  132.           font-variant: normal; text-transform: capitalize; color: #FFFFFF;       
  133.         }  
  134.           
  135.           
  136.          .style1  
  137.          {  
  138.              width: 177px;  
  139.          }  
  140.          .style2  
  141.          {  
  142.              width: 5px;  
  143.              color: #ff0000;  
  144.          }  
  145.           
  146.           
  147.          .style3  
  148.          {  
  149.              width: 32px;  
  150.          }  
  151.          .style4  
  152.          {  
  153.              width: 120px;  
  154.          }  
  155.          .style5  
  156.          {  
  157.              width: 4px;  
  158.          }  
  159.           
  160.           
  161.          .style6  
  162.          {  
  163.              width: 4px;     
  164.          }  
  165.           
  166.           
  167.     </style>  
  168. <div class="Heading">  
  169.     Working with EmptyDataTemplate, EditItemTemplate and others in GridView</div>  
  170.     <div class="ContentInside">  
  171.         <asp:ScriptManagerProxy ID="ScriptManagerProxy1" runat="server">  
  172.         </asp:ScriptManagerProxy>  
  173. </div>  
  174. <div class="ContentInside">  
  175.     <asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">  
  176.     <ContentTemplate>  
  177.     <table style="width:100%;">  
  178.         <tr>  
  179.             <td class="style3">  
  180.                  </td>  
  181.             <td class="style1">  
  182.                  </td>  
  183.             <td class="style6">  
  184.                  </td>  
  185.             <td class="style2">  
  186.                  </td>  
  187.             <td>  
  188.                  </td>  
  189.             <td>  
  190.                  </td>  
  191.             <td>  
  192.                  </td>  
  193.         </tr>  
  194.         <tr>  
  195.             <td class="style3">  
  196.                  </td>  
  197.             <td class="style1">  
  198.                 Enter Registration Number</td>  
  199.             <td class="style6">  
  200.                 :</td>  
  201.             <td class="style2">  
  202.                 *</td>  
  203.             <td>  
  204.                 <asp:TextBox ID="txtRegidtNo" runat="server" CssClass="TextBoxSize"   
  205.                     AutoPostBack="True" ontextchanged="txtRegidtNo_TextChanged"></asp:TextBox>  
  206.             </td>  
  207.             <td>  
  208.                  </td>  
  209.             <td>  
  210.                  </td>  
  211.         </tr>  
  212.         <tr>  
  213.             <td class="style3">  
  214.                  </td>  
  215.             <td class="style1">  
  216.                  </td>  
  217.             <td class="style6">  
  218.                  </td>  
  219.             <td class="style2">  
  220.                  </td>  
  221.             <td>  
  222.                 <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server"   
  223.                     ControlToValidate="txtRegidtNo" ErrorMessage="* Enter Registration Number"   
  224.                     ForeColor="Red" ValidationGroup="abc">* Enter Registration Number</asp:RequiredFieldValidator>  
  225.             </td>  
  226.             <td>  
  227.                  </td>  
  228.             <td>  
  229.                  </td>  
  230.         </tr>  
  231.         <tr>  
  232.             <td class="style3">  
  233.                  </td>  
  234.             <td class="style1">  
  235.                  </td>  
  236.             <td class="style6">  
  237.                  </td>  
  238.             <td class="style2">  
  239.                  </td>  
  240.             <td>  
  241.                 <asp:Label ID="lblMessage1" runat="server" Text="Message" Visible="False"></asp:Label>  
  242.             </td>  
  243.             <td>  
  244.                  </td>  
  245.             <td>  
  246.                  </td>  
  247.         </tr>  
  248.     </table>  
  249.    </ContentTemplate>  
  250.   </asp:UpdatePanel>  
  251. </div>  
  252. <div class="ContentInside">  
  253.     <table style="width:100%;">  
  254.         <tr>  
  255.             <td>  
  256.                  </td>  
  257.             <td>  
  258.                 Add Items To Below</td>  
  259.             <td>  
  260.                  </td>  
  261.             <td>  
  262.                  </td>  
  263.         </tr>  
  264.         <tr>  
  265.             <td>  
  266.                  </td>  
  267.             <td>  
  268.                 <asp:GridView ID="GridView1" runat="server" CellPadding="4" ForeColor="#333333"   
  269.                     GridLines="None" AutoGenerateColumns="False" ShowFooter="True"   
  270.                     ShowHeaderWhenEmpty="True" onrowcommand="GridView1_RowCommand"   
  271.                     AllowPaging="True" DataKeyNames="ID"   
  272.                     onpageindexchanging="GridView1_PageIndexChanging"   
  273.                     onrowdeleting="GridView1_RowDeleting" PageSize="4" Width="873px"   
  274.                     onrowediting="GridView1_RowEditing"   
  275.                     onrowcancelingedit="GridView1_RowCancelingEdit"   
  276.                     onrowupdating="GridView1_RowUpdating">  
  277.                     <AlternatingRowStyle BackColor="White" ForeColor="#284775" />  
  278.                     <Columns>  
  279.                         <asp:TemplateField HeaderText="ID">  
  280.                             <%--<EditItemTemplate>  
  281.                                 <asp:TextBox ID="TextBox5" runat="server" Text='<%# Bind("ID") %>'></asp:TextBox>  
  282.                             </EditItemTemplate>--%>  
  283.                             <ItemTemplate>  
  284.                                 <asp:Label ID="Label5" runat="server" Text='<%# Bind("ID") %>'></asp:Label>  
  285.                             </ItemTemplate>  
  286.                         </asp:TemplateField>  
  287.                         <asp:TemplateField HeaderText="Name">  
  288.                             <EditItemTemplate>  
  289.                                 <asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("Name") %>'></asp:TextBox>  
  290.                             </EditItemTemplate>  
  291.                             <FooterTemplate>  
  292.                                 <asp:TextBox ID="TextBox5" runat="server" CssClass="SmallTextBox"></asp:TextBox>  
  293.                             </FooterTemplate>  
  294.                             <ItemTemplate>  
  295.                                 <asp:Label ID="Label1" runat="server" Text='<%# Bind("Name") %>'></asp:Label>  
  296.                             </ItemTemplate>  
  297.                             <ControlStyle Width="100px" />  
  298.                             <FooterStyle Width="100px" />  
  299.                             <HeaderStyle Width="100px" />  
  300.                             <ItemStyle Width="100px" />  
  301.                         </asp:TemplateField>  
  302.                         <asp:TemplateField HeaderText="Mobile">  
  303.                             <EditItemTemplate>  
  304.                                 <asp:TextBox ID="TextBox2" runat="server" Text='<%# Bind("Mobile") %>'></asp:TextBox>  
  305.                             </EditItemTemplate>  
  306.                             <FooterTemplate>  
  307.                                 <asp:TextBox ID="TextBox6" runat="server" CssClass="SmallTextBox"></asp:TextBox>  
  308.                             </FooterTemplate>  
  309.                             <ItemTemplate>  
  310.                                 <asp:Label ID="Label2" runat="server" Text='<%# Bind("Mobile") %>'></asp:Label>  
  311.                             </ItemTemplate>  
  312.                             <ControlStyle Width="100px" />  
  313.                             <FooterStyle Width="100px" />  
  314.                             <HeaderStyle Width="100px" />  
  315.                             <ItemStyle Width="100px" />  
  316.                         </asp:TemplateField>  
  317.                         <asp:TemplateField HeaderText="EmailID">  
  318.                             <EditItemTemplate>  
  319.                                 <asp:TextBox ID="TextBox3" runat="server" Text='<%# Bind("EmailID") %>'></asp:TextBox>  
  320.                             </EditItemTemplate>  
  321.                             <FooterTemplate>  
  322.                                 <asp:TextBox ID="TextBox7" runat="server" Width="170px"></asp:TextBox>  
  323.                             </FooterTemplate>  
  324.                             <ItemTemplate>  
  325.                                 <asp:Label ID="Label3" runat="server" Text='<%# Bind("EmailID") %>'></asp:Label>  
  326.                             </ItemTemplate>  
  327.                             <ControlStyle Width="180px" />  
  328.                             <FooterStyle Width="180px" />  
  329.                             <HeaderStyle Width="180px" />  
  330.                             <ItemStyle Width="180px" />  
  331.                         </asp:TemplateField>  
  332.                         <asp:TemplateField HeaderText="Address">  
  333.                             <EditItemTemplate>  
  334.                                 <asp:TextBox ID="TextBox4" runat="server" Text='<%# Bind("Address") %>'></asp:TextBox>  
  335.                             </EditItemTemplate>  
  336.                             <FooterTemplate>  
  337.                                 <asp:TextBox ID="TextBox8" runat="server" CssClass="SmallTextBox" Width="150px"></asp:TextBox>  
  338.                             </FooterTemplate>  
  339.                             <ItemTemplate>  
  340.                                 <asp:Label ID="Label4" runat="server" Text='<%# Bind("Address") %>'></asp:Label>  
  341.                             </ItemTemplate>  
  342.                             <ControlStyle Width="150px" />  
  343.                             <FooterStyle Width="150px" />  
  344.                             <HeaderStyle Width="150px" />  
  345.                             <ItemStyle Width="150px" />  
  346.                         </asp:TemplateField>  
  347.                         <asp:TemplateField HeaderText="Add New">  
  348.                             <FooterTemplate>  
  349.                                 <asp:Button ID="btnAddGrid2" runat="server" CommandName="AddNew2"   
  350.                                     CssClass="SmallButton" Text="Add" />  
  351.                             </FooterTemplate>  
  352.                             <ControlStyle Width="70px" />  
  353.                             <FooterStyle Width="70px" />  
  354.                             <HeaderStyle Width="70px" />  
  355.                             <ItemStyle Width="70px" />  
  356.                         </asp:TemplateField>  
  357.                         <asp:TemplateField HeaderText="Edit / Delete ">  
  358.                             <EditItemTemplate>  
  359.                                 <asp:Button ID="btnGridUpdate" runat="server" CssClass="SmallButton"   
  360.                                     Text="Update" CommandName="Update" />  
  361.                                 <asp:Button ID="btnGridCancel" runat="server" CssClass="SmallButton"   
  362.                                     Text="Cancel" CommandName="Cancel" />  
  363.                             </EditItemTemplate>  
  364.                             <ItemTemplate>  
  365.                                 <asp:Button ID="btnGridEdit" runat="server" CssClass="SmallButton"   
  366.                                     Text="Edit" CommandName="Edit" />  
  367.                                 <asp:Button ID="btnGridDelete" runat="server" CssClass="SmallButton"   
  368.                                     Text="Delete" CommandName="Delete" OnClientClick="return confirm('Are You Sure You Want To Delete ?')" />  
  369.                             </ItemTemplate>  
  370.                             <HeaderStyle Width="130px" />  
  371.                         </asp:TemplateField>  
  372.                     </Columns>  
  373.                     <EditRowStyle BackColor="#999999" />  
  374.                     <EmptyDataTemplate>  
  375.                         <asp:TextBox ID="TextBox9" runat="server" CssClass="SmallTextBox"></asp:TextBox>  
  376.                         <asp:TextBox ID="TextBox10" runat="server" CssClass="SmallTextBox"></asp:TextBox>  
  377.                         <asp:TextBox ID="TextBox11" runat="server" CssClass="SmallTextBox"   
  378.                             Width="170px"></asp:TextBox>  
  379.                         <asp:TextBox ID="TextBox12" runat="server" CssClass="SmallTextBox"   
  380.                             Width="150px"></asp:TextBox>  
  381.                         <asp:Button ID="btnAddGrid1" runat="server" CommandName="AddNew1"   
  382.                             CssClass="SmallButton" Text="Add New" />  
  383.                     </EmptyDataTemplate>  
  384.                     <FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />  
  385.                     <HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />  
  386.                     <PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />  
  387.                     <RowStyle BackColor="#F7F6F3" ForeColor="#333333" />  
  388.                     <SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />  
  389.                     <SortedAscendingCellStyle BackColor="#E9E7E2" />  
  390.                     <SortedAscendingHeaderStyle BackColor="#506C8C" />  
  391.                     <SortedDescendingCellStyle BackColor="#FFFDF8" />  
  392.                     <SortedDescendingHeaderStyle BackColor="#6F8DAE" />  
  393.                 </asp:GridView>  
  394.             </td>  
  395.             <td>  
  396.                  </td>  
  397.             <td>  
  398.                  </td>  
  399.         </tr>  
  400.         <tr>  
  401.             <td>  
  402.                  </td>  
  403.             <td>  
  404.                 <asp:Label ID="lblMessage2" runat="server" Text="Message" Visible="False"></asp:Label>  
  405.             </td>  
  406.             <td>  
  407.                  </td>  
  408.             <td>  
  409.                  </td>  
  410.         </tr>  
  411.     </table>  
  412.     <table style="width: 100%;">  
  413.         <tr>  
  414.             <td class="style3">  
  415.                    
  416.             </td>  
  417.             <td class="style4">  
  418.                 <asp:Button ID="btnSaveAll" runat="server" CssClass="ClickButton"   
  419.                     Text="Save All" onclick="btnSaveAll_Click" ValidationGroup="abc" />  
  420.             </td>  
  421.             <td>  
  422.                  </td>  
  423.         </tr>  
  424.         <tr>  
  425.             <td class="style3">  
  426.                    
  427.             </td>  
  428.             <td class="style4">  
  429.                    
  430.             </td>  
  431.             <td class="style5">  
  432.                  </td>  
  433.             <td>  
  434.                 <asp:Label ID="lblMessage3" runat="server" Text="Message" Visible="False"></asp:Label>  
  435.             </td>  
  436.             <td>  
  437.                  </td>  
  438.         </tr>  
  439.         </table>  
  440. </div>  
  441. <div>  
  442. </div>  
  443. <div>  
  444. </div> 

I am using all the programming code here again:

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.UI;  
  6. using System.Web.UI.WebControls;  
  7. using System.Data;  
  8. using System.Data.SqlClient;  
  9. using System.Drawing;  
  10. using System.Configuration;  
  11.   
  12. public partial class Tech_Test_Controls_Gridview_Control_4 : System.Web.UI.UserControl  
  13. {  
  14.   
  15.     SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["CONN"].ConnectionString.ToString());  
  16.     //  
  17.     int i;  
  18.   
  19.     // declar Five variables here  
  20.     int ID;  
  21.     string Name, EmailID, Address;  
  22.     long Mobile;  
  23.     //  
  24.     DataTable Dt = new DataTable();  
  25.   
  26.     protected void Page_Load(object sender, EventArgs e)  
  27.     {  
  28.         if (!IsPostBack)  
  29.         {  
  30.             //Loading the Gridview  
  31.             LoadGridView();  
  32.         }  
  33.     }  
  34.   
  35.     private void LoadGridView()  
  36.     {  
  37.         // This Method will load the Gridview with Initial Data from the Temporary Table  
  38.         try  
  39.         {  
  40.             string Query = "select * from tbl_Temp_Gridview4";  
  41.             //  
  42.             SqlCommand cmd = new SqlCommand(Query, con);  
  43.             SqlDataAdapter da = new SqlDataAdapter();  
  44.             da.SelectCommand = cmd;  
  45.             //  
  46.             con.Open();  
  47.             da.Fill(Dt);  
  48.             con.Close();  
  49.             //  
  50.             GridView1.DataSource = Dt;  
  51.             GridView1.DataBind();  
  52.         }  
  53.         catch (Exception Exc)  
  54.         {  
  55.             lblMessage2.Visible = true;  
  56.             lblMessage2.ForeColor = Color.Red;  
  57.             lblMessage2.Text = " Application Error :  " + Exc.Message;  
  58.         }  
  59.   
  60.         finally  
  61.         {  
  62.             //  
  63.         }  
  64.     }  
  65.   
  66.     protected void txtRegidtNo_TextChanged(object sender, EventArgs e)  
  67.     {  
  68.         // this method is used to check if the Registration number already exist or not  
  69.         CheckRegistrationNo();  
  70.     }  
  71.   
  72.     private void CheckRegistrationNo()  
  73.     {  
  74.         // this method is used to check if the Registration number already exist or not  
  75.   
  76.         try  
  77.         {  
  78.             string Query = "select Regid from tbl_Gridview4 where Regid=@Regid";  
  79.             //  
  80.             SqlCommand cmd = new SqlCommand(Query, con);  
  81.             cmd.Parameters.AddWithValue("@Regid", txtRegidtNo.Text);  
  82.             con.Open();  
  83.             SqlDataReader dr = cmd.ExecuteReader();  
  84.             if (dr.Read())  
  85.             {  
  86.                 lblMessage1.Visible = true;  
  87.                 lblMessage1.ForeColor = Color.Red;  
  88.                 lblMessage1.Text = "This Registration Number is Already Exist, Please try Another ...";  
  89.                 //  
  90.                 dr.Close();  
  91.                 con.Close();  
  92.             }  
  93.             else  
  94.             {  
  95.                 dr.Close();  
  96.                 con.Close();  
  97.                 //  
  98.                 lblMessage1.Visible = false;  
  99.             }  
  100.              
  101.   
  102.         }  
  103.         catch (Exception Exc)  
  104.         {  
  105.             lblMessage1.Visible = true;  
  106.             lblMessage2.ForeColor = Color.Red;  
  107.             lblMessage1.Text = " Application Error :  " + Exc.Message;  
  108.         }  
  109.   
  110.         finally  
  111.         {  
  112.             //  
  113.         }  
  114.     }  
  115.     protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)  
  116.     {  
  117.         try  
  118.         {  
  119.             if (txtRegidtNo.Text == "")  
  120.             {  
  121.                 lblMessage1.Visible = true;  
  122.                 lblMessage1.ForeColor = Color.Red;  
  123.                 lblMessage1.Text = "Please Enter The Registration Number First";  
  124.             }  
  125.             else  
  126.             {  
  127.                 lblMessage1.Visible = false;  
  128.                 //  
  129.                 //check registration number  
  130.                 CheckRegistrationNo();  
  131.   
  132.                 GridViewRow row = (GridViewRow)(e.CommandSource as Button).NamingContainer;  
  133.   
  134.                 // this method will call first when the Gridview is Empty and the EmptyDataTemplate is Called here  
  135.   
  136.                 if (e.CommandName == "AddNew1")  
  137.                 {  
  138.                     // finding the value from the TextBox inside the EmptyDataTempalte  
  139.                     Name = (row.FindControl("TextBox9"as TextBox).Text;  
  140.                     Mobile = Convert.ToInt64((row.FindControl("TextBox10"as TextBox).Text);  
  141.                     EmailID = (row.FindControl("TextBox11"as TextBox).Text;  
  142.                     Address = (row.FindControl("TextBox12"as TextBox).Text;  
  143.                     //  
  144.                     string Query = "insert into tbl_Temp_Gridview4 (Name,Mobile,EmailID,Address) values(@Name,@Mobile,@EmailID,@Address)";  
  145.                     //  
  146.                     SqlCommand cmd = new SqlCommand(Query, con);  
  147.                     //  
  148.                     cmd.Parameters.AddWithValue("@Name", Name);  
  149.   
  150.                     cmd.Parameters.AddWithValue("@Mobile", Mobile);  
  151.   
  152.                     cmd.Parameters.AddWithValue("@EmailID", EmailID);  
  153.   
  154.                     cmd.Parameters.AddWithValue("@Address", Address);  
  155.                     //  
  156.                     con.Open();  
  157.                     i = cmd.ExecuteNonQuery();  
  158.                     con.Close();  
  159.                     //  
  160.                     if (i > 0)  
  161.                     {  
  162.                         //loading the Gridview  
  163.                         LoadGridView();  
  164.                         //  
  165.                         lblMessage2.Visible = true;  
  166.                         lblMessage2.ForeColor = Color.Green;  
  167.                         lblMessage2.Text = "One Record Add Sucessfully";  
  168.                     }  
  169.                 }  
  170.   
  171.                 // this method will called in FooterTemplate after one record is added to the Gridview  
  172.   
  173.                 if (e.CommandName == "AddNew2")  
  174.                 {  
  175.                     // finding the value from the TextBox inside the EmptyDataTempalte  
  176.                     Name = (row.FindControl("TextBox5"as TextBox).Text;  
  177.                     Mobile = Convert.ToInt64((row.FindControl("TextBox6"as TextBox).Text);  
  178.                     EmailID = (row.FindControl("TextBox7"as TextBox).Text;  
  179.                     Address = (row.FindControl("TextBox8"as TextBox).Text;  
  180.                     //  
  181.                     string Query = "insert into tbl_Temp_Gridview4 (Name,Mobile,EmailID,Address) values(@Name,@Mobile,@EmailID,@Address)";  
  182.                     //  
  183.                     SqlCommand cmd = new SqlCommand(Query, con);  
  184.                     //  
  185.                     cmd.Parameters.AddWithValue("@Name", Name);  
  186.   
  187.                     cmd.Parameters.AddWithValue("@Mobile", Mobile);  
  188.   
  189.                     cmd.Parameters.AddWithValue("@EmailID", EmailID);  
  190.   
  191.                     cmd.Parameters.AddWithValue("@Address", Address);  
  192.                     //  
  193.                     con.Open();  
  194.                     i = cmd.ExecuteNonQuery();  
  195.                     con.Close();  
  196.                     //  
  197.                     if (i > 0)  
  198.                     {  
  199.                         //loading the Gridview  
  200.                         LoadGridView();  
  201.                         //  
  202.                         lblMessage2.Visible = true;  
  203.                         lblMessage2.ForeColor = Color.Green;  
  204.                         lblMessage2.Text = "One Record Add Sucessfully";  
  205.                     }  
  206.   
  207.                 }  
  208.             }  
  209.   
  210.         }  
  211.         catch (Exception Exc)  
  212.         {  
  213.             lblMessage2.Visible = true;  
  214.             lblMessage2.ForeColor = Color.Red;  
  215.             lblMessage2.Text = " Application Error :  " + Exc.Message;  
  216.         }  
  217.   
  218.         finally  
  219.         {  
  220.             //  
  221.         }  
  222.     }  
  223.      
  224.     protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)  
  225.     {  
  226.         // Doing Paging here  
  227.         GridView1.PageIndex = e.NewPageIndex;  
  228.   
  229.         //Calling tne Function to load the Gridview  
  230.         LoadGridView();  
  231.     }  
  232.     protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)  
  233.     {  
  234.         if (con.State == ConnectionState.Open)  
  235.         {  
  236.             con.Close();  
  237.         }  
  238.   
  239.         try  
  240.         {  
  241.             //retrieving the DataKey name here  
  242.             ID = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Value.ToString());  
  243.   
  244.             string Query = "delete from tbl_Temp_Gridview4 where ID=@ID";  
  245.             //  
  246.             SqlCommand cmd = new SqlCommand(Query, con);  
  247.             cmd.Parameters.AddWithValue("@ID", ID);  
  248.             //  
  249.             con.Open();  
  250.             i = cmd.ExecuteNonQuery();  
  251.             if (i > 0)  
  252.             {  
  253.                 //Load the Gridview  
  254.                 LoadGridView();  
  255.             }  
  256.             con.Close();  
  257.   
  258.         }  
  259.         catch (Exception Exc)  
  260.         {  
  261.             lblMessage2.Visible = true;  
  262.             lblMessage2.ForeColor = Color.Red;  
  263.             lblMessage2.Text = " Application Error :  " + Exc.Message;  
  264.         }  
  265.   
  266.         finally  
  267.         {  
  268.             //  
  269.         }  
  270.     }  
  271.     protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)  
  272.     {  
  273.         //this line of code will open the Gridview in the Edit mode  
  274.         GridView1.EditIndex = e.NewEditIndex;  
  275.     }  
  276.     protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)  
  277.     {  
  278.         //this code will Cancel the row edit  
  279.         GridView1.EditIndex = -1;  
  280.   
  281.         //Loading the Gridview again  
  282.         LoadGridView();  
  283.     }  
  284.     protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)  
  285.     {  
  286.         try  
  287.         {  
  288.             //retrieving the DataKey name here  
  289.             ID = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Value.ToString());  
  290.   
  291.             // ((TextBox)GridView1.Rows[e.RowIndex].FindControl("TextBox2")).Text;  
  292.   
  293.             Name = (GridView1.Rows[e.RowIndex].FindControl("TextBox1"as TextBox).Text;  
  294.             Mobile = Convert.ToInt64((GridView1.Rows[e.RowIndex].FindControl("TextBox2"as TextBox).Text);  
  295.             EmailID = (GridView1.Rows[e.RowIndex].FindControl("TextBox3"as TextBox).Text;  
  296.             Address = (GridView1.Rows[e.RowIndex].FindControl("TextBox4"as TextBox).Text;  
  297.   
  298.             string Query = "update tbl_Temp_Gridview4 set Name=@Name, Mobile=@Mobile, EmailID=@EmailID, Address=@Address where ID=@ID ";  
  299.             //  
  300.             SqlCommand cmd = new SqlCommand(Query, con);  
  301.             //  
  302.             cmd.Parameters.AddWithValue("@Name", Name);  
  303.   
  304.             cmd.Parameters.AddWithValue("@Mobile", Mobile);  
  305.   
  306.             cmd.Parameters.AddWithValue("@EmailID", EmailID);  
  307.   
  308.             cmd.Parameters.AddWithValue("@Address", Address);  
  309.   
  310.             cmd.Parameters.AddWithValue("@ID", ID);  
  311.             //  
  312.             con.Open();  
  313.             i = cmd.ExecuteNonQuery();  
  314.             con.Close();  
  315.             //  
  316.             if (i > 0)  
  317.             {  
  318.                   
  319.                 // Closing the Editmode  
  320.                 GridView1.EditIndex = -1;  
  321.                 //  
  322.   
  323.                 //loading the Gridview  
  324.                 LoadGridView();  
  325.                 //  
  326.   
  327.                 lblMessage2.Visible = true;  
  328.                 lblMessage2.ForeColor = Color.Green;  
  329.                 lblMessage2.Text = "One Record Updated Sucessfully";  
  330.             }  
  331.   
  332.         }  
  333.         catch (Exception Exc)  
  334.         {  
  335.             lblMessage2.Visible = true;  
  336.             lblMessage2.ForeColor = Color.Red;  
  337.             lblMessage2.Text = " Application Error :  " + Exc.Message;  
  338.         }  
  339.   
  340.         finally  
  341.         {  
  342.             //  
  343.         }  
  344.          
  345.     }  
  346.     protected void btnSaveAll_Click(object sender, EventArgs e)  
  347.     {  
  348.         // fanally saving all data to the Main table in the database  
  349.         try  
  350.         {  
  351.             string RgNo;  
  352.             //  
  353.             if (con.State == ConnectionState.Open)  
  354.             {  
  355.                 con.Close();  
  356.             }  
  357.             if (txtRegidtNo.Text != "")  
  358.             {  
  359.                 RgNo = txtRegidtNo.Text;  
  360.   
  361.                 // this will find all the dat from the Gridview row  
  362.                 foreach (GridViewRow row in GridView1.Rows)  
  363.                 {  
  364.                     Name = (row.FindControl("Label1"as Label).Text;  
  365.                     Mobile = Convert.ToInt64((row.FindControl("Label2"as Label).Text);  
  366.                     EmailID = (row.FindControl("Label3"as Label).Text;  
  367.                     Address = (row.FindControl("Label4"as Label).Text;  
  368.                     //  
  369.   
  370.                     string Query = "insert into tbl_Gridview4 (Regid,Name,Mobile,EmailID,Address) values(@Regid,@Name,@Mobile,@EmailID,@Address)";  
  371.                     //  
  372.                     SqlCommand cmd = new SqlCommand(Query, con);  
  373.                     //  
  374.                     cmd.Parameters.AddWithValue("@Regid", RgNo);  
  375.   
  376.                     cmd.Parameters.AddWithValue("@Name", Name);  
  377.   
  378.                     cmd.Parameters.AddWithValue("@Mobile", Mobile);  
  379.   
  380.                     cmd.Parameters.AddWithValue("@EmailID", EmailID);  
  381.   
  382.                     cmd.Parameters.AddWithValue("@Address", Address);  
  383.                     //  
  384.                     con.Open();  
  385.                     i = cmd.ExecuteNonQuery();  
  386.                     con.Close();  
  387.                     //  
  388.                     if (i > 0)  
  389.                     {  
  390.                         //once all data is saved data from the temporary table need to deleted  
  391.                         if (con.State == ConnectionState.Open)  
  392.                         {  
  393.                             con.Close();  
  394.                         }  
  395.   
  396.                         string Query2 = "truncate table tbl_Temp_Gridview4 ";  
  397.                         //  
  398.                         SqlCommand cmd2 = new SqlCommand(Query2, con);  
  399.                         //  
  400.                         con.Open();  
  401.                         int B = cmd2.ExecuteNonQuery();  
  402.                         con.Close();  
  403.   
  404.                         //  
  405.                         //  
  406.                         lblMessage2.Visible = true;  
  407.                         lblMessage2.ForeColor = Color.Green;  
  408.                         lblMessage2.Text = "All Data Saved Sucessfully";  
  409.   
  410.                         //Loading the gridview again  
  411.                         LoadGridView();  
  412.   
  413.                         //clearing the Gridview  
  414.                         txtRegidtNo.Text = "";  
  415.   
  416.                     }  
  417.                 }  
  418.             }   
  419.         }  
  420.         catch (Exception Exc)  
  421.         {  
  422.             lblMessage2.Visible = true;  
  423.             lblMessage2.ForeColor = Color.Red;  
  424.             lblMessage2.Text = " Application Error :  " + Exc.Message;  
  425.         }  
  426.   
  427.         finally  
  428.         {  
  429.             //  
  430.         }    
  431.     }  
  432. }

Up Next
    Ebook Download
    View all
    Learn
    View all