Santry Technology Solutions, Content Management, DotNetNuke, SharePoint Consulting
Register | Login
Saturday, October 11, 2008

Sections
  
About Us
  
Partners
Downloads
  
 WWWCoder.com Resource Directory

Datagrid Operations
4/8/2005 12:48:29 PM

In this article we will see the most common use of the DataGrid control. We will be discussing the Add, Edit, and Update operations and their relationship with the DataGrid and database operations.

Introduction:

The Microsoft .NET framework ships with many useful controls. These controls makes the life of developer easy by providing them with the functionality they want.

Among the many controls is the DataGrid control which helps the developer to display the data on the screen in the format of an arranged table. The Datagrid control is one of the 3 templated controls provided by the Microsoft .NET framework. The other two controls are DataList and the Repeator control. Many new controls are being developed everyday but their basic idea is inherited from the classic DataGrid control.

In this article we will see the most common use of the datagrid control. Lets set up out datagrid.   

Setting up the Datagrid:

Lets first set up our datagrid.

  1. Drag and Drop the datagrid control from your toolbox to the webform.

  2. The datagrid will appear as a simple table.

  3. You can easily set the look of the control by selecting the Auto format features.

Okay your datagrid is set up, now lets add some columns.

Adding the Bound Columns:

Adding the bound colums in the datagrid is pretty simple.

  1. Right click on the datagrid and select Property Builder.

  2. Click on the Columns tab and uncheck "Generate columns automatically".

  3. Add three bound columns, give the columns some name in the column name field. And finally add the edit, update, and cancel buttons which can be found under the button option.

Note: Please also note that the button type should be link button or else it wont work.

Storing the database connection:

In this demo the database connection string is stored in the Web.config file. The database name is DBSnippets, which has one table known as tblPerson. Here is the web.config file:

<configuration>
<appSettings>
<add Key="ConnectionString" value="server=localhost;database=DBSnippets">
</appSettings>
</configuration>

Okay so up until now you have made the Datagrid and also saved the connection string in the web.config file. Now the time has come to code and handle the events.

Lets first create the BindData method which will retrieve the contents from the database and bind it to the control to be displayed on the screen. This will be one of the most important methods since it will be called whenever the page is loaded for the first time.

private void Page_Load(object sender, System.EventArgs e)
{
if(!Page.IsPostBack)
  {
   BindData();
 
}
 }

As you see the BindData method is called when the page is not posted back. Now lets see the BindData method in details.  

public void BindData()
{
SqlCommand myCommand = new SqlCommand("SP_SELECT_PERSONS",myConnection);
myCommand.CommandType = CommandType.StoredProcedure;
SqlDataAdapter myAdapter = new SqlDataAdapter(myCommand);
DataSet ds = new DataSet();
myAdapter.Fill(ds,"tblPerson");
myConnection.Open();
myCommand.ExecuteNonQuery();
myDataGrid.DataSource = ds;
myDataGrid.DataBind();
myConnection.Close();
}


Explanation of the BindData method: 

  1. First we made a SqlCommand object and named it myCommand. The SqlCommand object takes the name of a stored procedure as an input and the SqlConnection which provides information on how to connect to the SQL database.
  2. We feed the command object to the DataAdapter object named as myAdapter.
  3. A dataset is declared which is filled with the result of the Stored procedure.
  4. myDataGrid.DataBind() binds the datagrid to the page. Don't forget to bind the grid or else it won't be displayed. 
  5. Later we opened the connection and execute the query.

Lets see the stored procedure.

Stored Procedure:

CREATE PROCEDURE SP_SELECT_PERSONS
AS
SELECT * FROM tblPerson 
GO

As you can see that the above Stored Procedure is pretty simple. All we are doing is selecting all the columns from the table person.

Lets now make the Edit method which will display textboxes inside the datagrid so that a user can insert data. This sort of editing is also known as Inline editing.

Making datagrid editable is pretty simple. All you to do is to code few lines in the EditCommand event of the datagrid. You can view all the events supported by DataGrid by selecting properties and than selecting the Thunder/Flash yellow sign at the top of the properties window.

Lets call our Edit DataGrid event Edit_DataGrid.

private void Edit_DataGrid(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e)
{
// We use CommandEventArgs e to get the row which is being clicked
// This also changes the DataGrid labels into Textboxes so user can edit them
myDataGrid.EditItemIndex = e.Item.ItemIndex;
// Always bind the data so the datagrid can be displayed.
BindData();
}

When the Edit link button is clicked your DataGrid will look something like this:

As you see when you click the edit link the update and the cancel link button automatically appears.

Lets now see the code for the Cancel Event.

Cancel event is used when you are in the edit mode and you change your mind about editing. So you click the cancel link button and the Datagrid returns back to its original condition.

  private void Cancel_DataGrid(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e)
{
// All we do in the cancel method is to assign '-1' to the datagrid editItemIndex
// Once the edititemindex is set to '-1' the datagrid returns back to its original condition
myDataGrid.EditItemIndex = -1;
BindData();
}

Okay now we come to a slightly difficult step. We will carefully look at the Update method and see how it works.


private void Update_DataGrid(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e)
{
System.Web.UI.WebControls.TextBox cName = new System.Web.UI.WebControls.TextBox();
cName = (System.Web.UI.WebControls.TextBox) e.Item.Cells[1].Controls[0];
SqlCommand myCommand = new SqlCommand("SP_UpdatePerson",myConnection);
myCommand.CommandType = CommandType.StoredProcedure;
myCommand.Parameters.Add(new SqlParameter("@PersonName",SqlDbType.NVarChar,50));
myCommand.Parameters["@PersonName"].Value = cName.Text;
myConnection.Open();
myCommand.ExecuteNonQuery();
myConnection.Close();
myDataGrid.EditItemIndex = -1;
BindData();
}

Lets now dig into this method and see what's going on with this code.

  1. The name of the method as you can see is Update_DataGrid, this event is fired when you click the update link button which appears after clicking the edit button.
  2. We declare a TextBox type and call it cName. The reason of declaring a TextBox is that the value that we want is inside the TextBox control which is inside the DataGrid control.
  3. Later we made the SqlCommand object which takes stored procedure "SP_UpdatePerson", which will be discussed later in this tutorial.
  4. After marking the command object with the stored procedure we passed the parameter which is PersonName.
  5. Finally we execute the Query and set the editItemIndex property of the DataGrid '-1' which will bring the datagrid back to its original form i.e. without any textboxes.
  6. Don't forget to bind the datagrid.

Update Stored Procedure:

CREATE PROCEDURE SP_UpdatePerson

@PersonName nvarchar(50)
AS
UPDATE tblPerson SET PersonName = @PersonName WHERE PersonName = @PersonName;

Selecting Item from the Datagrid:

Another cool feature of the Datagrid control is that you can select any row from the datagrid and it will be displayed as the highlighted row in the grid.

The highlight row event is called SelectedIndexChanged event. The event is called when the select column is clicked. The select column can be added to the datagrid using the property builder, just like we added "edit/cancel/update" link buttons.

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

This method is pretty simple. When the datagrid select link button is pressed. We retrieve the item from the datagrid which is residing on the same row on which the link button is pressed. As we can see above in the code that we are retrieving the value from the first column of the datagrid.

I hope you all liked the article happy programming !

About the Author:

Mohammad Azam, also known as Azamsharp have been programming in .NET for 4 years. He is the author of several articles which can be viewed on his website www.azamsharp.cjb.net . Apart from the articles Azamsharp is also the Top 50 poster on Microsoft official forums (www.asp.net).

At present Azamsharp is completing his undergraduate degree in Computer Science from University of Houston and also working as a .NET consultant for cSoft Technologies.

You can reach Azamsharp at xMohammadAzamx@yahoo.com

 


Page Options:
format for printing  Format for Printer
email article  Email Page
add to your favorites   Add to Favorites
How would you rate the quality of this content?
Poor - - Excellent
Comments?
Overall Rating:
Comments Left:
Left on 10/8/2008 7:29:20 AM by Anonymous
Comments: its very usefull........thnxxxxxxx
Left on 4/18/2008 12:59:39 PM by Anonymous
Comments: this code wich language?

No ratings available.
Left on 4/17/2008 10:25:41 AM by Anonymous
Comments: I could not put this example working for me
No ratings available.
Left on 11/28/2007 2:42:12 AM by Anonymous
Comments: enti sooper archana raajamandri lo
No ratings available.
Left on 11/28/2007 2:41:36 AM by Anonymous
Comments: enti sooper archana
No ratings available.
Left on 11/28/2007 1:03:25 AM by Anonymous
Comments: edisaav edchinattu undi
No ratings available.
Left on 11/27/2007 3:38:44 AM by Anonymous
Comments: rajahmundry lo SOOOOPER andi
Left on 11/27/2007 3:38:13 AM by Anonymous
Comments: worst!!!!!!!!!!! but excellent
Left on 4/24/2007 2:26:01 AM by Anonymous
Comments: i saw the code above its excellent, but i just wanted to ask u that is the code behind file coded in vb or c#.
Left on 2/13/2007 2:27:18 AM by Anonymous
Comments: good
Left on 10/12/2006 4:04:49 PM by Anonymous
Comments: really superb
No ratings available.
Left on 9/28/2006 3:01:26 AM by Anonymous
Comments:
Left on 8/30/2006 12:33:25 AM by Anonymous
Comments: update is not updating the personname
No ratings available.
Left on 8/7/2006 7:28:08 AM by Anonymous
Comments: Nice Gaining of knowledge from this
Left on 7/31/2006 2:41:04 PM by Anonymous
Comments: Great Article!It is wonderful for people who are getting stuck on small things, write some more article like this

thanks
No ratings available.
Left on 4/23/2006 9:05:39 AM by Anonymous
Comments: System.Web.UI.WebControls.TextBox cName = new System.Web.UI.WebControls.TextBox();
cName = (System.Web.UI.WebControls.TextBox) e.Item.Cells[1].Controls[0];

Programming in .NET for 4 years?
HAHAHA! you should be joking...
Left on 3/29/2006 8:18:32 AM by Anonymous
Comments: Excellent Article
Left on 3/22/2006 7:02:52 AM by Anonymous
Comments: gud code sir i need it in a VB.net clearly can u plz kindly
No ratings available.
Left on 7/10/2005 6:01:26 AM by Anonymous
Comments: You should also provide the code for using link button in data grid,rest of the article is fine and is of some value

Left on 6/24/2005 1:50:48 PM by Anonymous
Comments: Your piece of code doesn't help a beginner at all :(
Left on 6/21/2005 1:10:11 PM by Anonymous
Comments: i did the same thing but when i tried to extract the new value that i keyed into the text box it gave me back the original existing value in the cell. The textbox did not return back the new value. I tried this in both the bound and unbound mode and i had the same results.
Left on 6/13/2005 9:08:53 AM by Anonymous
Comments: Concise enough to get the point across to me, a newby ASP.NET guy!
Left on 6/6/2005 7:18:34 AM by Anonymous
Comments: easy to use..Good enough
No ratings available.
Left on 5/26/2005 6:45:36 AM by Anonymous
Comments: nothing is working waste
Left on 5/23/2005 11:13:00 PM by Anonymous
Comments: Nice Gaining of knowledge from this site
Left on 5/18/2005 5:36:33 PM by Anonymous
Comments: "In this article we will see the most common use of the DataGrid control. We will be discussing the Add, Edit, and Update operations."

Where is the ADD module in your code? you had mentioned in the begining that you will be describing an ADD module.
Left on 5/17/2005 5:42:15 AM by Anonymous
Comments: totally there so many mistakes in this article
No ratings available.
Left on 5/5/2005 2:49:15 AM by Anonymous
Comments: simple and understandable.
Left on 4/27/2005 5:16:43 AM by Anonymous
Comments: nice that given example
No ratings available.
Left on 4/27/2005 12:57:09 AM by Anonymous
Comments: problem in understanding...not user friendly
Left on 4/21/2005 12:30:34 AM by Anonymous
Comments: Great Article...
No ratings available.
Left on 4/19/2005 9:37:06 AM by Anonymous
Comments: Microsoft had crummy instructions that didn't work. Your instructions were easy to use and they worked!
  

 Latest Articles
  

 Latest News
  

 

Spotlight
Syndication

 


 


Digg This
 


DotNetNuke Platinum Benefactor

  
 

 Terms Of Use | Privacy Statement
 Copyright 2008 - Santry Technology Solutions, Box 172, Girard, PA 16417, (814) 774-0970