Click here to Skip to main content
15,914,013 members
Articles / Web Development / ASP.NET
Article

DataGrid's Common Operations

Rate me:
Please Sign up or sign in to vote.
2.27/5 (21 votes)
5 Aug 2004 59.1K   26   7
Datagrid's common operations include editing, updating, deleting etc.

Introduction

In this article, I will share the code for most common operations of a DataGrid control. These operations include editing, updating, selecting, deleting, sorting and paging. Before you write any code, you need to add the columns into your DataGrid. Please see the images below to see how to do that.

Sample screenshot

Sample screenshot

Now we are ready. So let's start with the Page_Load event.

Page_Load Event Code

C#
if(!Page.IsPostBack) 
{ 
  Bind_DataGrid(); 
}

Bind_DataGrid Method Code

C#
public void Bind_DataGrid() 
{ 
  SqlCommand myCommand = 
     new SqlCommand("SELECT * FROM Categories",myConnection); 
  myCommand.CommandType = CommandType.Text; 
  SqlDataAdapter myAdapter = new SqlDataAdapter(myCommand);
  DataSet ds = new DataSet(); 

  myAdapter.Fill(ds,"Categories"); 


  myConnection.Open(); 
  myCommand.ExecuteReader(); 
  myDataGrid.DataSource = ds; 
  myConnection.Close();

  try 
  { 
    myDataGrid.DataBind(); 
  } 
  catch 
  { 
    myDataGrid.CurrentPageIndex = 0; 
    Bind_DataGrid();
  }
}

EditCommand Event Code

C#
// This Method sets the datagrid in Edit mode.
private void Edit_DataGrid(object source, 
    System.Web.UI.WebControls.DataGridCommandEventArgs e)
{
  myDataGrid.EditItemIndex = e.Item.ItemIndex; 
  Bind_DataGrid();
}

CancelCommand Event Code

C#
// This event is fired when the cancel is clicked. 
private void Cancel_DataGrid(object source, 
       System.Web.UI.WebControls.DataGridCommandEventArgs e)
{
  myDataGrid.EditItemIndex = -1; 
  Bind_DataGrid(); 
}

UpdateCommand Event Code

C#
private void Update_DataGrid(object source, 
      System.Web.UI.WebControls.DataGridCommandEventArgs e)
{

  // using full name because of Ambigous Reference 
  System.Web.UI.WebControls.TextBox cName = 
      new System.Web.UI.WebControls.TextBox(); 
  System.Web.UI.WebControls.TextBox cID = 
      new System.Web.UI.WebControls.TextBox(); 

  cID = (System.Web.UI.WebControls.TextBox) e.Item.Cells[0].Controls[0];
  cName = (System.Web.UI.WebControls.TextBox) e.Item.Cells[1].Controls[0];

  Label3.Text = cID.Text; 
  // Have to do it later 
  SqlCommand myCommand = new SqlCommand("UpdateCat",myConnection); 
  myCommand.CommandType = CommandType.StoredProcedure;
  myCommand.Parameters.Add(new SqlParameter("@CategoryID",
          SqlDbType.NVarChar,4)); 
  myCommand.Parameters["@CategoryID"].Value = Convert.ToInt32( cID.Text ); 
  myCommand.Parameters.Add(new SqlParameter("@CategoryName",
          SqlDbType.NVarChar,15)); 
  myCommand.Parameters["@CategoryName"].Value = cName.Text; 
  myConnection.Open(); 
  myCommand.ExecuteNonQuery(); 
  myConnection.Close(); 

  myDataGrid.EditItemIndex = -1;

  Bind_DataGrid();
}

SelectedIndexChanged Event Code

C#
// This event is fired when the Select is clicked
private void Select_DataGrid(object sender, System.EventArgs e)
{
  // prints the value of the first cell in the DataGrid 
  Label2.Text += myDataGrid.SelectedItem.Cells[0].Text;
}

PageIndexChanged Event Code

C#
// This event is fired when the paging is done.
private void Paging_DataGrid(object source, 
       System.Web.UI.WebControls.DataGridPageChangedEventArgs e)
{
  // There is a Problem in Paging if any page is  
  // completed deleted it will throw theException I will try to fix it 
  // and Repost the working Solution of Paging. 

  myDataGrid.CurrentPageIndex = e.NewPageIndex; 
  Bind_DataGrid();
}

SortCommand Event Code

The sorting is done by clicking on the column header. Clicking first time will sort the DataGrid in the ascending order and clicking twice will sort the DataGrid in descending order.

C#
// This event is fired when the header is clicked for sorting
private void Sort_DataGrid(object source, 
    System.Web.UI.WebControls.DataGridSortCommandEventArgs e)
{
  SqlCommand myCommand = 
      new SqlCommand("SELECT * FROM Categories",myConnection); 
  myCommand.CommandType = CommandType.Text; 
  SqlDataAdapter myAdapter = new SqlDataAdapter(myCommand);
  DataSet ds = new DataSet(); 

  myAdapter.Fill(ds,"Categories"); 
  DataView dv = new DataView(ds.Tables["Categories"]); 

  // Two way sorting LOGIC 

  if( (numberDiv%2) == 0 ) 
    dv.Sort = e.SortExpression + " " + "ASC"; 
  else 
    dv.Sort = e.SortExpression + " " + "DESC"; 
  numberDiv++; 

  myDataGrid.DataSource = dv;
  myDataGrid.DataBind();
}

DeleteCommand Event Code

C#
// Deletes the specific Row 
private void Delete_DataGrid(object source, 
     System.Web.UI.WebControls.DataGridCommandEventArgs e)
{
  string s = e.Item.Cells[0].Text;

  SqlCommand myCommand = 
      new SqlCommand("DELETE FROM Categories WHERE CategoryID="+s,myConnection);
  myCommand.CommandType = CommandType.Text;
  myConnection.Open();
  myCommand.ExecuteNonQuery(); 
  myConnection.Close();
  // Binds the grid so that change can be seen
  Bind_DataGrid();
}

Enjoy the code! I hope you all will use it one way or the other.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
Web Developer
United States United States
My name is Mohammad Azam and I have been developing iOS applications since 2010. I have worked as a lead mobile developer for VALIC, AIG, Schlumberger, Baker Hughes, Blinds.com and The Home Depot. I have also published tons of my own apps to the App Store and even got featured by Apple for my app, Vegetable Tree. I highly recommend that you check out my portfolio. At present I am working as a lead instructor at DigitalCrafts.




I also have a lot of Udemy courses which you can check out at the following link:
Mohammad Azam Udemy Courses

Comments and Discussions

 
GeneralProblem in Deleting Data !! Pin
samshah51223-Jul-07 23:45
samshah51223-Jul-07 23:45 
Generalgoog Pin
Ravindraravuir11-Oct-06 23:58
Ravindraravuir11-Oct-06 23:58 
QuestionHmm....Poor, don't you think? Pin
Alexandru Savescu5-Aug-04 23:07
Alexandru Savescu5-Aug-04 23:07 
AnswerRe: Hmm....Poor, don't you think? Pin
azamsharp11-Aug-04 11:31
azamsharp11-Aug-04 11:31 
GeneralRe: Hmm....Poor, don't you think? Pin
Anonymous12-Jan-05 9:23
Anonymous12-Jan-05 9:23 
GeneralRe: Hmm....Poor, don't you think? Pin
azamsharp13-Jan-05 14:55
azamsharp13-Jan-05 14:55 
numberDiv is a static variable which is declared publically. Please use viewstate for this purpose.



Mohammad Azam
.net Web Developer
Undergraduate Student ( Computer Science )
University of Houston Main Campus
email: iamazam@hotmail.com
azamsharp.cjb.net

GeneralRe: Hmm....Poor, don't you think? Pin
Anonymous3-Aug-05 0:35
Anonymous3-Aug-05 0:35 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.