Sunday, August 11, 2019

How to enable in-place editing with validation control in a GridView in ASP.NET

Step - 1 : Create New Project.

Go to File > New > Project > Select asp.net web forms application > Entry Application Name > Click OK.

Step-2: Add a Database.

Go to Solution Explorer > Right Click on App_Data folder > Add > New item > Select SQL Server Database Under Data > Enter Database name > Add.

Step-3: Create table for fetch data.

Open Database > Right Click on Table > Add New Table > Add Columns > Save > Enter table name > Ok.
In this example, I have used one tables as below

Step-4: Add Entity Data Model.

Go to Solution Explorer > Right Click on Project name form Solution Explorer > Add > New item > Select ADO.net Entity Data Model under data > Enter model name > Add.
A popup window will come (Entity Data Model Wizard) > Select Generate from database > Next >

Chose your data connection > select your database > next > Select tables > enter Model Namespace > Finish.

Step-5: Add a Webpage and Design for Show Data in Gridview which rows are editable.

Go to Solution Explorer > Right Click on Project name form Solution Explorer > Add > New item > Select web form/ web form using master page under Web > Enter page name > Add.

HTML Code 
  1. <h3>Inline Edit / Delete with validation control in Gridview in ASP.NET</h3>
  2. <br />
  3. <div>
  4. <asp:GridView ID="gvContact" runat="server" AutoGenerateColumns="false" CellSpacing="5" CellPadding="5"
  5. DataKeyNames="ContactID"
  6. OnRowCancelingEdit="gvContact_RowCancelingEdit"
  7. OnRowDeleting="gvContact_RowDeleting"
  8. OnRowEditing="gvContact_RowEditing"
  9. OnRowUpdating="gvContact_RowUpdating">
  10. <Columns>
  11. <asp:TemplateField HeaderText="SL No.">
  12. <ItemTemplate>
  13. <%#Container.DataItemIndex + 1 %>
  14. </ItemTemplate>
  15. </asp:TemplateField>
  16. <asp:TemplateField HeaderText="Contact Person">
  17. <ItemTemplate>
  18. <%#Eval("ContactPerson") %>
  19. </ItemTemplate>
  20. <EditItemTemplate>
  21. <asp:TextBox ID="txtContactPerson" runat="server" Text='<%#Bind("ContactPerson") %>'></asp:TextBox>
  22. <asp:RequiredFieldValidator ID="rftxtContactPerson" runat="server"
  23. ControlToValidate="txtContactPerson" ForeColor="Red" SetFocusOnError="true"
  24. ErrorMessage="Please provide Contact Person." ValidationGroup="Update">*</asp:RequiredFieldValidator>
  25. </EditItemTemplate>
  26. </asp:TemplateField>
  27. <asp:TemplateField HeaderText="Contact No">
  28. <ItemTemplate>
  29. <%#Eval("ContactNo") %>
  30. </ItemTemplate>
  31. <EditItemTemplate>
  32. <asp:TextBox ID="txtContactNo" runat="server" Text='<%#Bind("ContactNo") %>'></asp:TextBox>
  33. <asp:RequiredFieldValidator ID="rftxtContactNo" runat="server"
  34. ControlToValidate="txtContactNo" ForeColor="Red" SetFocusOnError="true"
  35. ErrorMessage="Please provide Contact No." ValidationGroup="Update">*</asp:RequiredFieldValidator>
  36. </EditItemTemplate>
  37. </asp:TemplateField>
  38. <asp:TemplateField HeaderText="Email ID">
  39. <ItemTemplate>
  40. <%#Eval("EmailID") %>
  41. </ItemTemplate>
  42. <EditItemTemplate>
  43. <asp:TextBox ID="txtEmailID" runat="server" Text='<%#Bind("EmailID") %>'></asp:TextBox>
  44. <asp:RegularExpressionValidator ID="rgtxtEmailID" runat="server"
  45. ControlToValidate="txtEmailID" ForeColor="Red" SetFocusOnError="true"
  46. ErrorMessage="Please provide valid email id." ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*">*</asp:RegularExpressionValidator>
  47. </EditItemTemplate>
  48. </asp:TemplateField>
  49. <asp:TemplateField>
  50. <%-- This is for Show Edit & Delete Button --%>
  51. <ItemTemplate>
  52. <asp:LinkButton ID="lbtnEdit" runat="server" CommandName="Edit"
  53. CommandArgument='<%#Eval("ContactID")%>'>Edit</asp:LinkButton>
  54. &nbsp;
  55. <asp:LinkButton ID="lbtnDelete" runat="server" CommandName="Delete"
  56. CommandArgument='<%#Eval("ContactID") %>'
  57. OnClientClick="javascript: return confirm('Are you really want to delete?')">Delete</asp:LinkButton>
  58. </ItemTemplate>
  59. <EditItemTemplate>
  60. <%-- This is for show Update & Cancel Button after click on Edit Button (Edit Mode) --%>
  61. <asp:LinkButton ID="lbtnUpdate" runat="server" CommandName="Update"
  62. CommandArgument='<%#Eval("ContactID")%>'>Update</asp:LinkButton>
  63. &nbsp;
  64. <asp:LinkButton ID="lbtnCancel" runat="server" CommandName="Cancel">Cancel</asp:LinkButton>
  65. </EditItemTemplate>
  66. </asp:TemplateField>
  67. </Columns>
  68. </asp:GridView>
  69. </div>

Step-6: Write following code in Page_Load event for Show data in Gridview.


  1. protected void Page_Load(object sender, EventArgs e)
  2. {
  3. if (!IsPostBack)
  4. {
  5. PopulateData(); // Populate All Contacts from Database and show in gridview
  6. }
  7. }
Here is the function...
  1. private void PopulateData()
  2. {
  3. using (MyDatabaseEntities dc = new MyDatabaseEntities())
  4. {
  5. gvContact.DataSource = dc.Contacts.ToList();
  6. gvContact.DataBind();
  7. }
  8. }

Step-7: Write below code in Gridview RowEditing event for make particular row editable.


  1. protected void gvContact_RowEditing(object sender, GridViewEditEventArgs e)
  2. {
  3. // This event is for open edit item templete for particular row
  4. gvContact.EditIndex = e.NewEditIndex;
  5. PopulateData();
  6. }

Step-8: Write below code in Gridview RowCancelingEdit event for cancel row editing.


  1. protected void gvContact_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
  2. {
  3. // This event is for cancel editing
  4. gvContact.EditIndex = -1;
  5. PopulateData();
  6. }

Step-9: Write below code in Gridview RowDeleting event for delete record from database.


  1. protected void gvContact_RowDeleting(object sender, GridViewDeleteEventArgs e)
  2. {
  3. // This event is for Deleting for particular row
  4. int ContactID = Convert.ToInt32(gvContact.DataKeys[e.RowIndex]["ContactID"].ToString());
  5. using (MyDatabaseEntities dc = new MyDatabaseEntities())
  6. {
  7. var c = dc.Contacts.Where(a => a.ContactID.Equals(ContactID)).FirstOrDefault();
  8. if (c!= null)
  9. {
  10. dc.Contacts.Remove(c);
  11. }
  12. dc.SaveChanges();
  13. PopulateData();
  14. }
  15. }

Step-10: Write below code in Gridview RowUpdating event for update database record.


  1. protected void gvContact_RowUpdating(object sender, GridViewUpdateEventArgs e)
  2. {
  3. // Here I will update record
  4. int ContactID = Convert.ToInt32(gvContact.DataKeys[e.RowIndex]["ContactID"].ToString());
  5.  
  6. // Find Textbox for get updated values
  7. TextBox txtContactPerson = (TextBox)gvContact.Rows[e.RowIndex].FindControl("txtContactPerson");
  8. TextBox txtContactNo = (TextBox)gvContact.Rows[e.RowIndex].FindControl("txtContactNo");
  9. TextBox txtEmailID = (TextBox)gvContact.Rows[e.RowIndex].FindControl("txtEmailID");
  10.  
  11. if (txtContactPerson != null && txtContactNo != null && txtEmailID != null)
  12. {
  13. if (txtContactPerson.Text.Trim() != "" && txtContactNo.Text.Trim() != "")
  14. {
  15. using (MyDatabaseEntities dc = new MyDatabaseEntities())
  16. {
  17. Contact c = dc.Contacts.Where(a => a.ContactID==ContactID).FirstOrDefault();
  18. if (c != null)
  19. {
  20. c.ContactPerson = txtContactPerson.Text.Trim();
  21. c.ContactNo = txtContactNo.Text.Trim();
  22. c.EmailID = txtEmailID.Text.Trim();
  23.  
  24. dc.SaveChanges();
  25. }
  26. }
  27. PopulateData();
  28. }
  29. }
  30. }

Step-11: Run Application.

No comments:

Post a Comment

How to register multiple implementations of the same interface in Asp.Net Core?

 Problem: I have services that are derived from the same interface. public interface IService { } public class ServiceA : IService { ...