Grid view in asp.net all Edit,Update,RowEditCancel,Delete by anil nain 9416077273Abstract: This program tells us how write code for Grid View Example with Edit,Update,RowEditCancel,Delete,Delete Multiple Rows using Check Box, CheckAll/UnCheckAll item of checkbox using dataset.Assumptions-We are using SQL Server Express/SQL SERVER 2005 editions as Database.Table Name- StudentsFields- RollNo, SName, Course, Doj(Date of Joining), FeePaid –For detail description of Database goto bottom of page.Take GridView control on page and set the ID property to GridView1.Go to property builder by right click on GridView -> Show Smart Tag -> Edit Columns. Uncheck Auto-Generate Field from the Property window.Add three TemplateField Column for RollNo, SName, Course, Doj(Date of Joining), FeePaid, & Delete Button in template field. Add Edit button from CommandField Group from Property Window.TemplateField Colums have ItemTemplate, Alternating Item Template, Edit Template, Header Template, Footer Template. Each template columns Item Template field contains Label Control & Edit Template contains TextBox control for Editing item. Set the Binding Field name to the Text Property of both controls for each template field to the respective Database Column Name i.e Eval("SName"). Similarly others also.Set the DataKeyNames property of GridView to Primary Key Column of DataBase i.e. RollNo. This property binds the database column field value to each row of gridview as a Unique Identifier.Set the data bindings for Delete Button for CommandArgument Eval("RollNo"); for saving the ID column value from database for fetching the ID field value while Deleting the Record. Set the CommandName property to Delete Button to CMDDelete.
The CommandName property can contain any string name which can be used to recognize the type of command invoked from gridview. Because when any of the event generated in GridVeiw it fires RowCommand Event. In this event we have to handle the Delete Button Code. Instead if you are using default Delete Button of GridView then register for RowDeleting event of GridView and for accessing Unique ID columnvalue from database you need to fetch the id from DataKeys collection of GridView. For e.g.int RollNo = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Value); Place the Textbox control in the grids Footer template for Adding new record. Set the CommandName to CMDAdd for Add button.Register events for Edit, Update, Cancel button of gridview – RowEditing, RowUpdating, RowCancelEditing. View in GridViewTo view data in gridview is very simple. Just create a DataSet using SqlDataAdapter’s Fill method and set the GridViews DataSource Property to DataSet.Create a Method to Bind the GridView to DataSource named BindGrid. This method fetches data from the GetStudents method which returns DataSet from Employees table.Call the BindGrid on Page_Load in !IsPostBack block to fill the grid by default.//Code for displaying data in grid view private void BindGrid()
{ GridView1.DataSource = GetStudents(); GridView1.DataBind(); }
//Code for connectioning to the server private DataSet GetStudents() { DataSet ds = new DataSet(); SqlConnection conn = new SqlConnection("Data Source=saibaba;Initial Catalog=GENERALEXAMPLE;User ID=sa;pwd=sa1"); SqlDataAdapter da = new SqlDataAdapter("Select * From Students", conn); try
{ da.Fill(ds); return ds; } catch (Exception ex) { throw new Exception(ex.Message); } finally { conn.Close(); conn.Dispose(); } return null; } protected void Page_Load(object sender, EventArgs e) { if (!Page.IsPostBack) { BindGrid(); } } Edit in GridViewFor Editing Register RowEditing event of GridView. To switch the normal mode to Edit mode of gridview EditIndex property plays important role. EditIndex specifies which row is in edit mode by setting RowIndex to it. By default EditIndex of gridview is -1 (Normal mode). If you want to edit 3rd Row – then set the EditIndex to 2 (Row index starts from 0,1,2..).After setting editindex refresh the grid by calling BinGrid. GridViewEditEventArgs object knows the current row index so getting row index of the selected row in gridveiw is not big deal;
just e.NewEditIndex (e object of GridViewEditEventArgs).protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{ GridView1.EditIndex = e.NewEditIndex; BindGrid();
}Cancel in GridViewFor Cancel just reset the GridView editindex to default i.e. -1 and refresh the grid.protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{ GridView1.EditIndex = -1; BindGrid();
}Update in GridViewFor Update register RowUpdating event of the gridview. Find the Unique id for updating the row from DataKeys collection of gridview.protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
int RollNo = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Value);
//Find Text boxex
TextBox TSName1 = GridView1.Rows[e.RowIndex].FindControl("TSName") as TextBox;
TextBox TCourse1 = GridView1.Rows[e.RowIndex].FindControl("TCourse") as TextBox;
TextBox TDoj1 = GridView1.Rows[e.RowIndex].FindControl("TDoj") as TextBox;
TextBox TFeePaid1 = GridView1.Rows[e.RowIndex].FindControl("TFeePaid") as TextBox;
if (TSName1 != null && TCourse1 != null && TDoj1 != null && TFeePaid1 != null)
UpdateStudent(RollNo, TSName1.Text.Trim(), TCourse1.Text.Trim(), DateTime.Parse(TDoj1.Text.Trim()),Decimal.Parse(TFeePaid1.Text.Trim())); GridView1.EditIndex = -1; BindGrid(); }Custom Delete in GridViewFor Delete register RowCommand event of the gridview. Find the Unique id for deleting the row from DataKeys collection of gridview. Check for CommanName and invoke delete method for the selected row.Add in GridViewAdding from GridView is just some trick with Footer Template. I added textboxes and a add button in the footer row of the gridview. When u are in Normal mode it is visible else it is invisible to synchronize between edit and add. Like Updating find the Textbox and pass the values to Addemployee method likeprotected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e) { if (e.CommandName.Equals("CMDDelete")) { int RollNo = Convert.ToInt32(e.CommandArgument); DeleteStudent(RollNo); //Refresh Grid BindGrid(); } else if (e.CommandName.Equals("CMDAdd")) { TextBox TSName1 = GridView1.FooterRow.FindControl("TSName") as TextBox; TextBox TCourse1 = GridView1.FooterRow.FindControl("TCourse") as TextBox; TextBox TDoj1 = GridView1.FooterRow.FindControl("TDoj") as TextBox;
TextBox TFeePaid1 = GridView1.FooterRow.FindControl("TFeePaid") as TextBox; if (TSName1 != null && TCourse1 != null && TDoj1 != null && TFeePaid1 != null) { AddStudent(TSName1.Text.Trim(), TCourse1.Text.Trim(), DateTime.Parse(TDoj1.Text), Decimal.Parse(TFeePaid1.Text.Trim())); BindGrid(); }
}}
See below for completed code including Check All/ Uncheck All, Deleting multiple rows
ASPX Page
1 comment:
Insert, Update and Delete data cells and rows to GridView
Post a Comment