C# Tutorials and offshore development in India
    Tutorials   Resources   Forum   Reviews   Communities   Interview   Jobs   Projects   Training   Your Ad Here    
Silverlight Games | Mentor | Code Converter | Articles | Code Factory | Computer Jokes | Members | Peer Appraisal | IT Companies | Bookmarks | Polls | Revenue Sharing | Lobby | Gift Shop |


Prizes & Awards
My Profile



Active Members
TodayLast 7 Days more...






Resources » Articles » ASP.NET/Web Applications »

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


Posted Date: 08 Nov 2005    Resource Type: Articles    Category: ASP.NET/Web Applications
Author: Harish RanganathanMember Level: Gold    
Rating: 1 out of 5Points: 10



Introduction


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.

Exploring the Controls defined


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!



Summary


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.






Responses


No responses found. Be the first to respond and make money from revenue sharing program.

Feedbacks      
Popular Tags   What are tags ?   Search Tags  
Sign In to add tags.
(No tags found.)

Post Feedback


This is a strictly moderated forum. Only approved messages will appear in the site. Please use 'Spell Check' in Google toolbar before you submit.
You must Sign In to post a response.
Next Resource: Grid View Paging and Sorting
Previous Resource: MVC design pattern using ASP.NET
Return to Discussion Resource Index
Post New Resource
Category: ASP.NET/Web Applications


Post resources and earn money!
 
Related Resources



dotNet Slackers

About Us    Contact Us    Privacy Policy    Terms Of Use