ASP.NET DataGrid Template Columns with Image Button - Master Details View - Part II

This article is in continuation with Part I which discusses about having Image Buttons within template columns in ASP.NET DataGrid. If you have come to this article without checking it, please check Part I.

Okay, additionally, we had three more controls viz., Button "btnAddCustomer" which is actually used to add new Customer; TextBox "txtCustomerName" which is the TextBox for entering or editing customer name; Button "btnSaveCustomer " which is used for saving the new Customer information.

In the DataGrid, we had Image Buttons for Edit / Delete / Update.

While Delete is as simple as removing the record from the Database, Edit & Update are inter-connected to each other since, whatever information that is being edited needs to be updated to the Database after the necessary changes.

Edit / Delete / Update Buttons are common for each and every record in the DataGrid and hence can form a part of the Template Column.

However, Add is an independent process which is not dependant on any of the rows and hence we have it as a separate button, outside the DataGrid. We will reuse the TextBox "txtCustomerName" both for Adding as well as Editing.


So, let us start with the first operation:-

Binding the DataGrid
===============

using System.Data.SqlClient;

private void Page_Load(object sender, System.EventArgs e)
{

If (! IsPostBack)
{
BindDataGrid();
}

}


private void BindDataGrid() // method which will Bind the Datagrid.
{
SqlConnection objCon = new SqlConnection (place your connection string here);

SqlCommand objCmd = new SqlCommand("select CustomerId, CustomerName from
Customer", objCon);

DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = objCmd;


da.Fill(ds);

DataGrid1.DataSource = ds;
DataGrid1.DataBind();


}

As it is evident, we are just creating a DataSet and assigning it to the DataGrid's DataSource property after filling the DataSet with an SqlDataAdapter.

Add
===

For Adding a new Customer, we just need to click on the Add Button which is outside the DataGrid. It would clear up the TextBox "txtCustomerName" if it already has any value.

Additionally, we defined the Button "btnSaveCustomer" as Visible="False". On click of the "Add" Button, we need to set its visiblity to "True".

I am not going to discuss about the Validations as it is beyond the scope of this article.

So, upon clicking the Button "btnSaveCustomer", we need to get the value from "txtCustomerName" and write a simple method which would insert the Customer Name to the Database. Once the insertion is successfull, we can hide the "btnSaveCustomer" by settings its visibility to "False" again.

As simple as that, I am not going to discuss the code or implementation for this operation.

Edit / Update / Delete Operations
========================

Since we have defined the OnItemCommand="DataGrid1ItemCommand" for the DataGrid, any image button, we click will only call this event. We now have to define this event in the codebehind

protected void DataGrid1ItemCommand(object source, DataGridCommandEventArgs e)
{
string command = e.CommandName;
switch(command)
{
case "Edit":

EditCustomer(System.Convert.ToInt16(e.CommandArgument));
break;

case "Update"

UpdateCustomer(System.Convert.ToInt16(e.CommandArgument));
break;

case "Delete":

DeleteCustomer(System.Convert.ToInt16(e.CommandArgument));
break;

default:
break;

}

}

As you can see, the above method retrieves a string "CommandName" from the DataGridCommandEventArgs and does a Switch..Case based on the "CommandName".

We have defined the "CommandName" as "Edit", "Delete" and "Update" for the respective Buttons in the DataGrid Template Column Definition. Hence, whatever Image Button is clicked over there, will pass the CommandName.

Additionally, I have written methods EditCustomer, UpdateCustomer & DeleteCustomer which we will discuss a little later. But, you can see that I pass the e.CommandArgument to all these methods, which would relatively fetch the CustomerId, since we have defined the CommandArgument for the Image Buttons as CustomerId.

With this CustomerId, I can do all my operations such as Edit / Update / Delete etc., I am just doing a type conversion of the CustomerId (CommandArgument) to integer to cater to the Database design where CustomerId is an integer column.

We will just briefly see, what each of these methods look like, below:-

private void EditCustomer(int CustomerId)
{

SqlConnection objCon = new SqlConnection (place your connection string here);

SqlCommand objCmd = new SqlCommand("select CustomerName from
Customer where CustomerId =" + CustomerId, objCon);


SqlDataReader objRdr;

objCon.Open();

objRdr = objCmd.ExecuteReader();

if(objRdr.Read())
{
txtCustomerName.Text = objRdr["CustomerName"].ToString();
}


objRdr.Close();
objCon.Close();
}

The above method retrieves the Customer Name based on the Customer Id and assigns it to the TextBox "txtCustomerName". Thereafter, we can make changes to the Customer name by editing the Text in the TextBox.

Similarly, we can write the UpdateCustomer method and DeleteCustomer by modifying the Select statement to Update statement and Delete statement respectively.

For update, we need to pass both CustomerName as well as CustomerId. Customer Name can be retrieved from the TextBox "txtCustomerName" and CustomerId is what we pass to this method.

For Delete statement, we just need the CustomerId which is passed to the method.

One thing to note is that we need to highlight the Row that is being Edited, once the user clicks on the Edit button. This is to make sure that after clicking Edit and making changes, the user doesnt click on any other record's update button. Else, the record will be updated incorrectly.

To do, that we need to add this line of code below the case "Edit": line in the DataGrid1ItemCommand method as defined above:-

e.Item.BackColor = System.Drawing.Color.Aqua; // or any other color

Thus we can ensure that the user updates the correct row.

This article discussed how we can have an Image Button within DataGrid Template Columns and provide a Master - Details View for Edit / Update / Delete operations in a DataGrid.

I have written the code without proper try..catch blocks, stored procedure instead of open SQL Statements and other best practices just for the sake for simplicity.

As already acknowledged, this is just one of the ways to do it and there are many other ways to implement an Editable DataGrid.

Some good references for DataGrid articles are

1. An Extensive examination of the DataGrid Web Control

2. ASP.NET DataGrid Girl!

Comments and suggestions are welcome.

Cheers and Happy Programming !!!

Print | posted on Tuesday, November 8, 2005 8:02 AM

Comments on this post

# re: ASP.NET DataGrid Template Columns with Image Button - Master Details View - Part II

Requesting Gravatar...
Nice! it solves a lot of questions.
Left by Danish Sami on Nov 20, 2006 9:29 AM

# re: ASP.NET DataGrid Template Columns with Image Button - Master Details View - Part II

Requesting Gravatar...
I wanna show the corrosponding Itemcell[3]'s text when i click the imagebutton.plz help me.i m using TableCell cell3=e.item.cell[3].text on itemcommand event but it's not working.
Left by Neeraj on Dec 13, 2006 4:11 AM

# re: ASP.NET DataGrid Template Columns with Image Button - Master Details View - Part II

Requesting Gravatar...
I wanna show the corrosponding Itemcell[3]'s text when i click the imagebutton.plz help me.i m using TableCell cell3=e.item.cell[3].text on itemcommand event but it's not working.
Left by Neeraj on Dec 13, 2006 4:11 AM

# re: ASP.NET DataGrid Template Columns with Image Button - Master Details View - Part II

Requesting Gravatar...
Complex. but interesting. Where can I find Part I ???
Left by Bjk on Feb 26, 2007 2:27 PM

# re: ASP.NET DataGrid Template Columns with Image Button - Master Details View - Part II

Left by Bjk on Feb 26, 2007 2:32 PM

# re: ASP.NET DataGrid Template Columns with Image Button - Master Details View - Part II

Requesting Gravatar...
I was having a similar issue before, check out my tutorial on how to add a button or other ASP.NET control to a Grid.

http://www.ivrtechgroup.com/blog/post/CRM-Custom-Fields.aspx

I provided some pictures on how to bind data from the Data Source to the ASP .Net control as well.
Left by Tim on Jan 27, 2009 3:02 AM

# re: ASP.NET DataGrid Template Columns with Image Button - Master Details View - Part II

Requesting Gravatar...
i click the imagebutton.plz help me
Left by mario oyunları on Sep 21, 2009 10:47 AM

# re: ASP.NET DataGrid Template Columns with Image Button - Master Details View - Part II

Requesting Gravatar...
aLINMASI GEREKEN GÜZEL BİR ŞEY
Left by meksika biberi zayıflama hapı on May 31, 2010 11:27 PM

# re: ASP.NET DataGrid Template Columns with Image Button - Master Details View - Part II

Requesting Gravatar...
DİYETSİZ BİR ÜRÜN
Left by meksika biberi zayıflama hapı on May 31, 2010 11:28 PM

# re: ASP.NET DataGrid Template Columns with Image Button - Master Details View - Part II

Requesting Gravatar...


This is good only if you limited number of scripts
Left by meksika biberi zayiflama hapi on Jun 01, 2010 12:25 AM

Your comment:

 (will show your gravatar)