Click here to Skip to main content
Licence 
First Posted 5 Aug 2004
Views 47,391
Bookmarked 26 times

DataGrid's Common Operations

By | 5 Aug 2004 | Article
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

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

Bind_DataGrid Method Code

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

// 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

// 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

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

// 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

// 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.

// 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

// 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

About the Author

azamsharp

Web Developer

United States United States

Member

I am the founder of knowledge base website, HighOnCoding, GridViewGuy, RefactorCode.com and ScreencastADay.com.
 
HighOnCoding is a website which will get you high legally with useful information. There are tons of articles, videos and podcasts hosted on HighOnCoding.
 
HighOnCoding.com www.HighOnCoding.com
 

My Blog:

Blog

 

Buy my iPhone app ABC Pop


Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board. (secure sign-in)
 
Search this forum  
 FAQ
    Noise  Layout  Per page   
  Refresh
GeneralProblem in Deleting Data !! Pinmembersamshah51223:45 23 Jul '07  
Generalgoog PinmemberRavindraravuir23:58 11 Oct '06  
QuestionHmm....Poor, don't you think? PinmemberAlexandru Savescu23:07 5 Aug '04  
AnswerRe: Hmm....Poor, don't you think? Pinmemberazamsharp11:31 11 Aug '04  
GeneralRe: Hmm....Poor, don't you think? PinsussAnonymous9:23 12 Jan '05  
GeneralRe: Hmm....Poor, don't you think? Pinmemberazamsharp14:55 13 Jan '05  
GeneralRe: Hmm....Poor, don't you think? PinsussAnonymous0:35 3 Aug '05  

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

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

Permalink | Advertise | Privacy | Mobile
Web01 | 2.5.120517.1 | Last Updated 6 Aug 2004
Article Copyright 2004 by azamsharp
Everything else Copyright © CodeProject, 1999-2012
Terms of Use
Layout: fixed | fluid