This article going to explain how to implement griview’s row updating,deleting,editing and create new process in Asp.Net. Take a look at the following sample source code. Download Source Here.
First Step : You can add following gridview layout sample code in your asp.net file (aspx). You have to notice that gridview is working with TemplateField and ItemTemplate and also create new button is outside of Gridview . In the cs file process, you will see sample as detailed.
<asp:GridView ID="grd_Icoders" runat="server" AutoGenerateColumns="False" OnRowDataBound="grd_Icoders_RowDataBound" OnRowDeleting="grd_Icoders_RowDeleting" OnRowEditing="grd_Icoders_RowEditing" OnRowCancelingEdit="grd_Icoders_RowCancelingEdit" OnRowUpdating="grd_Icoders_RowUpdating" DataKeyNames="RowGuid" Width="100%"> <Columns> <asp:TemplateField> <HeaderStyle /> <ItemTemplate> <asp:LinkButton ID="lnkb_Edit" runat="server" CommandName="Edit" CausesValidation="false">Edit</asp:LinkButton> <asp:Label ID="lbl_Separator" runat="server" Text="|"></asp:Label> <asp:LinkButton ID="lnkb_Delete" runat="server" CausesValidation="false" Text="Del" CommandName="Delete" OnClientClick="return confirm('Are you sure ?')"></asp:LinkButton> </ItemTemplate> <EditItemTemplate> <asp:LinkButton ID="lnkb_Update" runat="server" CommandName="Update" CausesValidation="false">Update</asp:LinkButton> <asp:Label ID="lbl_Separator" runat="server" Text="|"></asp:Label> <asp:LinkButton ID="lbl_Cancel" runat="server" CommandName="Cancel" CausesValidation="false">Cancel</asp:LinkButton> </EditItemTemplate> <ItemStyle HorizontalAlign="center" Width="10%" /> </asp:TemplateField> <asp:TemplateField> <HeaderTemplate> <asp:Label ID="lbl_Icoders" runat="server" Text="Icoders"></asp:Label> </HeaderTemplate> <HeaderStyle HorizontalAlign="Left" /> <ItemTemplate> <asp:Label ID="lbl_Icoders" runat="server"></asp:Label> </ItemTemplate> <EditItemTemplate> <asp:TextBox ID="txt_Icoders" runat="server" Width="95%"></asp:TextBox> </EditItemTemplate> <ItemStyle Width="65%" /> </asp:TemplateField> <asp:TemplateField> <HeaderTemplate> <asp:Label ID="lbl_Date" runat="server" Text="Date"></asp:Label> </HeaderTemplate> <HeaderStyle HorizontalAlign="Left" /> <ItemTemplate> <asp:Label ID="lbl_Date" runat="server"></asp:Label> </ItemTemplate> <EditItemTemplate> <asp:Label ID="lbl_Date" runat="server"></asp:Label> </EditItemTemplate> <ItemStyle Width="10%" /> </asp:TemplateField> <asp:TemplateField> <HeaderTemplate> <asp:Label ID="lbl_Icodersator" runat="server" Text="Modified By"></asp:Label> </HeaderTemplate> <HeaderStyle HorizontalAlign="Left" /> <ItemTemplate> <asp:Label ID="lbl_Icodersator" runat="server"></asp:Label> </ItemTemplate> <EditItemTemplate> <asp:Label ID="lbl_Icodersator" runat="server"></asp:Label> </EditItemTemplate> <ItemStyle Width="15%" /> </asp:TemplateField> </Columns> <EmptyDataTemplate> <table border="0" cellpadding="1" cellspacing="0" width="100%"> <tr style="background-color: #a0a0a0; height: 25px"> <td style="width: 10%"> </td> <td style="width: 65%"> <asp:Label ID="lbl_Icoders" runat="server" Text="Icoders"></asp:Label> </td> <td style="width: 10%"> <asp:Label ID="lbl_Date" runat="server" Text="Date"></asp:Label> </td> <td style="width: 15%"> <asp:Label ID="lbl_Icodersator" runat="server" Text="Modified By"></asp:Label> </td> </tr> </table> </EmptyDataTemplate> </asp:GridView> <table border="0" cellpadding="0" cellspacing="0" width="100%"> <tr style="height: 20px"> <td align="right"> <asp:Button ID="btn_New" runat="server" Text="New" OnClick="btn_New_Click" Width="75px" /> </td> </tr> </table>
Applying Gridview row databound event for databinding process as following way.
protected void grd_Icoders_RowDataBound(object sender, GridViewRowEventArgs e) { // DataRow if (e.Row.RowType == DataControlRowType.DataRow) { e.Row.Attributes.Add("onMouseOver", "GridView_Row_MouseOver(this);"); e.Row.Attributes.Add("onMouseOut", "GridView_Row_MouseOut(this);"); e.Row.Style.Add("cursor", "hand"); // Icoders if (e.Row.FindControl("lbl_Icoders") != null) { Label lbl_Icoders = (Label)e.Row.FindControl("lbl_Icoders"); lbl_Icoders.Text = DataBinder.Eval(e.Row.DataItem, "Icoders").ToString(); } // Icoders if (e.Row.FindControl("txt_Icoders") != null) { TextBox txt_Icoders = (TextBox)e.Row.FindControl("txt_Icoders"); txt_Icoders.Text = (DataBinder.Eval(e.Row.DataItem, "Icoders").ToString() == string.Empty ? string.Empty : DataBinder.Eval(e.Row.DataItem, "Icoders").ToString()); } // Date if (e.Row.FindControl("lbl_Date") != null) { Label lbl_Date = (Label)e.Row.FindControl("lbl_Date"); lbl_Date.Text = ((DateTime)DataBinder.Eval(e.Row.DataItem, "Date")).ToString("dd/MM/yyyy"); } // Icodersator if (e.Row.FindControl("lbl_Icodersator") != null) { Label lbl_Icodersator = (Label)e.Row.FindControl("lbl_Icodersator"); lbl_Icodersator.Text = DataBinder.Eval(e.Row.DataItem, "Icodersator").ToString(); } } }
When user click the edit button, the gridview mode needed to change for user editable. In that case you can apply as following way.
protected void grd_Icoders_RowEditing(object sender, GridViewEditEventArgs e) { grd_Icoders.DataSource = dsSample.Tables["TableName"]; grd_Icoders.EditIndex = e.NewEditIndex; grd_Icoders.DataBind(); }
After finishing changes value in edit mode, you needed to make updated for those of changes reflected to database. In that case you apply as following way.
protected void grd_Icoders_RowUpdating(object sender, GridViewUpdateEventArgs e) { //// Get rowguid from update row Guid rowGuid = new Guid(grd_Icoders.DataKeys[e.RowIndex].Values[0].ToString()); foreach (DataRow drUpdating in dsSample.Tables["TableName"].Rows) { if (drUpdating.RowState != DataRowState.Deleted) { if ((Guid)drUpdating["RowGuid"] == rowGuid) { // Find controls on edited row TextBox txt_Icoders = (TextBox)grd_Icoders.Rows[e.RowIndex].FindControl("txt_Icoders"); TextBox txt_Date = (TextBox)grd_Icoders.Rows[e.RowIndex].FindControl("txt_Date"); TextBox txt_Icodersator = (TextBox)grd_Icoders.Rows[e.RowIndex].FindControl("txt_Icodersator"); drUpdating["Icoders"] = txt_Icoders.Text; drUpdating["ModifiedDate"] = DateTime.Now.ToString("yyyy-MM-dd"); drUpdating["ModifiedBy"] = "UserID"; // you can get from login information // Refresh data in GridView grd_Icoders.DataSource = dsSample.Tables["TableName"]; grd_Icoders.EditIndex = -1; grd_Icoders.DataBind(); continue; } } } // Delete data from database bool result = SampleIcoders.Save(dsSample); if (result) { // Save changed to session Session["dsSample"] = dsSample; } else { } }
When user click the delete button, you have to determind that what row user has been clicked. After that based on user deleted row index, you will going to make delete process and reflect to database and gridview disaply data as well. Take a look at the sample as followings.
protected void grd_Icoders_RowDeleting(object sender, GridViewDeleteEventArgs e) { // Get ID from deleted row,this is the way determind for specific ID,code etc Guid rowGuid = new Guid(grd_Icoders.DataKeys[e.RowIndex].Values[0].ToString()); // Delete selected row for (int i = dsSample.Tables["TableName"].Rows.Count - 1; i >= 0; i--) { DataRow drSampleIcoders = dsSample.Tables["TableName"].Rows[i]; if (drSampleIcoders.RowState != DataRowState.Deleted) { if ((Guid)drSampleIcoders["RowGuid"] == rowGuid) { drSampleIcoders.Delete(); continue; } } } // Access from your class file and try to do update or save to database. bool result = SampleIcoders.SaveMethod(dsSample); if (result) { // Refresh data in GridView grd_Icoders.DataSource = dsSample.Tables["TableName"]; grd_Icoders.DataBind(); } else { } }
When user click the cancel button, needed to go back to original stage.In that case, we can apply RowCancelingEdit event to perform this process. Detailed as followings.
protected void grd_Icoders_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e) { // Determind the changes row. Guid rowGuid = new Guid(grd_Icoders.DataKeys[e.RowIndex].Values[0].ToString()); for (int i = dsSample.Tables["TableName"].Rows.Count - 1; i >= 0; i--) { DataRow drCanceling = dsSample.Tables["TableName"].Rows[i]; if (drCanceling.RowState != DataRowState.Deleted) { if ((Guid)drCanceling["RowGuid"] == rowGuid && drCanceling.RowState == DataRowState.Added) { drCanceling.Delete(); continue; } } } // Refresh data in GridView grd_Icoders.DataSource = dsSample.Tables["TableName"]; grd_Icoders.EditIndex = -1; grd_Icoders.DataBind(); // Refresh data to dataset. Session["dsSample"] = dsSample; }
When user click the new button, the gridview mode should be ready to create new row and ready to input data. In that case, new button clcik process implemented as following way. I hope that you will get some idea and easy to reference.
protected void btn_New_Click(object sender, EventArgs e) { DataRow drNew = dsSample.Tables["TableName"].NewRow(); drNew["RowGuid"] = Guid.NewGuid(); drNew["Icoders"] = string.Empty; drNew["CreatedDate"] = DateTime.Now.ToString("yyyy-MM-dd"); drNew["CreatedBy"] = "UserID"; // you can get from login information drNew["ModifiedDate"] = DateTime.Now.ToString("yyyy-MM-dd"); drNew["ModifiedBy"] = "UserID"; // you can get from login information dsSample.Tables["TableName"].Rows.Add(drNew); grd_Icoders.DataSource = dsSample.Tables["TableName"]; grd_Icoders.EditIndex = grd_Icoders.Rows.Count; grd_Icoders.DataBind(); Session["dsSample"] = dsSample; }
The following sample code is working with javascript, that will help you get idea for when user click gridview mouseover and mouseout, you can apply with following way. That function calling usage is in gridview rowdatabound event.
<script type="text/javascript" language="javascript"> function GridView_Row_MouseOver(rowindex) { // OnMouseover function change some color var tmpGridViewRowBGColor = rowindex.style.backgroundColor; rowindex.style.backgroundColor = "#000000"; } // OnMouseout function show back to original background color. function GridView_Row_MouseOut(rowindex) { rowindex.style.backgroundColor = tmpGridViewRowBGColor; } </script>