JG Vimalan's Blog

It is all about coding!

Clickable and Double Clickable ASP.NET 4.0 GridView

In this post, I will show you how to make a GridView clickable and double clickable. Also, I will show how to read the selected row values using java script.

I assume that you have a gridview in your asp.net page and the datasource is properly set.

Step 1:

In the GridView RowCreated event, set the onclick and ondblclick events as shown below. selectRow(this); and showDetail(this); are javascript functions and I have expained about them later in this post.

protected void GridView1RowCreated(object sender, GridViewRowEventArgs e)
            if (e.Row.RowType == DataControlRowType.DataRow)
                e.Row.Attributes.Add(“onclick”, “selectRow(this);”);

Step 2:

In the GridView RowDataBound event, set the onmouseover and onmouseout attributes as shown below. mouseIn(this); and mouseOut(); are javascript functions and I have expained about them later in this post.

protected void GridView1RowDataBound(object sender, GridViewRowEventArgs e)
            if (e.Row.RowType == DataControlRowType.DataRow)
             e.Row.Attributes.Add(“onmouseover”, “mouseIn(this);”);
         e.Row.Attributes.Add(“onmouseout”, “mouseOut();”);

Thats all! Now your work at code behind is over. Lets look at the javascript functions used for reading the selected gridview row and launching a popup when the row is double clicked.

Step 3:

The javascript functions are given below.

<script type=”text/javascript”>

function mouseIn(row) {
    document.body.style.cursor = ‘pointer’;
function mouseOut() {
    document.body.style.cursor = ‘auto’;   

//This function will provide you an idea on reading gridview values in
function selectRow(row) {
var index = row.rowIndex – 1; //subract 1 to get the selected row index
var numberOfRows = row.length;
var gridViewObj = document.getElementById(“<%=GridView1.ClientID %>”);
var name = ”;
var gender = ”;

row.style.backgroundColor = “yellow”; //this makes the selected row as yellow color

//specific to browsers other than firefox
            if (document.all) {
                name = gridViewObj.rows[index].cells[1].innerText;
                gender = gridViewObj.rows[index].cells[2].innerText;               
            //specific to firefox
            else {
                name = gridViewObj.rows[index].cells[1].textContent;
                gender = gridViewObj.rows[index].cells[2].textContent;              

function showDetail(row) {

//read the values from gridview as shown.
//open a page as popup and pass the values in query string


August 28, 2012 Posted by | ASP.NET, C#.NET, VS 2010 | | 1 Comment

Connect to DB2 database using Enterprise Library 5.0 – Data Access Application Block

In this post, I will show you how to connect to DB2 database using Enterprise Library 5.0 – Data Access Application Block. The code snippets are developed using C#, ASP.NET and Visual Studio 2010.

Step 1:

Install Enterprise Library 5.0 and IBM Db2 Client (I am using 9.7 fix 6) in your development system.

Step 2:

Add reference to Microsoft.Practices.EnterpriseLibrary.Data in your project.

Step 3:

In the web.config file, add the connection string for target DB2 database,

<add name=”DB2Conn” connectionString=”Dsn=CustomerDb2;uid=abcdefg;pwd=tempassword”
providerName=”System.Data.Odbc” />

Step 4:

In the app settings, add the Db2 schema name as shown below,

<add key=”DB2SchemaName” value=”DevSerDb2″ />

In my case, the schema name is DevSerDb2.

Step 5:

In my Utility class, I added properties for accessing the values from Web.config file as shown below,

public class Utility

internal static string GetDB2SchemaName
get { return ConfigurationManager.AppSettings[“DB2SchemaName”]; }

internal static string GetDB2ConnectionName
get { return string.Format(“DB2Conn”); }

Step 6:

In your data access class, add reference as shown below,

using Microsoft.Practices.EnterpriseLibrary.Data;

Step 7:

I have a stored procedure in Db2 which accepts 2 parameters and returns multiple rows of records. The code snippet for connecting to it and retrieving the values is as follows,

public DataSet Search(string userId, string firstName)
DataSet resultSet = null;
StringBuilder sql = new StringBuilder(“Call “).Append(Utility.GetDB2SchemaName).Append(“.SP_CUSTOMER_LIST(?,?)”);
Database database = DatabaseFactory.CreateDatabase(Utility.GetDB2ConnectionName);
using (DbCommand dbCommand = database.GetStoredProcCommand(sql.ToString()))
OdbcParameter userIdParam = new OdbcParameter(“@userId”, OdbcType.VarChar, 24);
userIdParam.Direction = ParameterDirection.Input;
userIdParam.Value = userId;

OdbcParameter firstNameParam = new OdbcParameter(“@firstName”, OdbcType.VarChar, 24);
firstNameParam.Direction = ParameterDirection.Input;
firstNameParam.Value = firstName;

resultSet = database.ExecuteDataSet(dbCommand).Tables[0];
return resultSet;


August 28, 2012 Posted by | C#.NET, DB2, Enterprise Library 5.0 | 1 Comment

Email critical exceptions using Enterprise Library 5.0 Logging Application Block

I got a task where I need to email specific exceptions (like database connectivity issues) to an email address.  The idea is to notify the support team immediately about the critical issues. My project was developed using Visual Studio 2010, ASP.NET and C#.  In order to complete this task,  I used Microsoft Enterprise Library 5.o Logging Application Block. The steps are very simple and it is given below,

a) Install Microsoft Enterprise Library 5.0 in your system. You can download from : http://www.microsoft.com/en-us/download/details.aspx?id=15104

b) Add reference to Microsoft.Practices.EnterpriseLibrary.Logging in your project.

c) Launch ‘Edit Enterprise Library V5 Configuration’ wizard by right clicking the web.config file as shown below,

d) Under ‘Blocks’, select ‘Add Logging Settings’. This will display default logging settings in the wizard.

e) Now define the exception categories (Lets say, General, Error, Critical etc). The idea is to send email only if the exception category is Critical. Now add the email trace listener and provide necessary details as shown in the image below. Add a log message formatter. In my case, I added Text Formatter. In email trace listener set the formatter as ‘Text Formatter’. In Critical category, set the Listeners as Email Trace Listener. Finally, the settings should look as shown below,

f) Save the file and close it. The settings will be displayed in the web.config file.

g) In the code, add multiple catch blocks as shown below and set the category to ‘Critical’ for those exceptions you want to capture in email.

Now, whenever there is a null reference exception, an email will be sent.

Sample email with exception is given below,


August 26, 2012 Posted by | C#.NET, Enterprise Library 5.0 | , , | Leave a comment

Always display GridView header

In ASP.NET 4.0 GridView, Microsoft has added a cool property called ‘ShowHeaderWhenEmpty’. Using this property is very simple.  According to the description of this property, the header will be displayed only if you have <EmptyDataTemplate> set in your gridview. Header will not be displayed only just by setting the ‘ShowHeaderWhenEmpty’ property to true.  My sample gridview is given below,

<asp:GridView ID=”UserInformationViewer” runat=”server”
ForeColor=”#333333″ CellPadding=”4″ ShowHeaderWhenEmpty=”True”
style=”margin-right: 0px” AutoGenerateColumns=”False”>
<AlternatingRowStyle BackColor=”White” ForeColor=”#284775″ />
<EditRowStyle BackColor=”#999999″ />
<FooterStyle BackColor=”#5D7B9D” Font-Bold=”True” ForeColor=”White” />
<HeaderStyle BackColor=”#5D7B9D” Font-Bold=”True” ForeColor=”White” />
<PagerStyle BackColor=”#284775″ ForeColor=”White” HorizontalAlign=”Center” />
<RowStyle BackColor=”#F7F6F3″ ForeColor=”#333333″ />
<SelectedRowStyle BackColor=”#E2DED6″ Font-Bold=”True” ForeColor=”#333333″ />
<SortedAscendingCellStyle BackColor=”#E9E7E2″ />
<SortedAscendingHeaderStyle BackColor=”#506C8C” />
<SortedDescendingCellStyle BackColor=”#FFFDF8″ />
<SortedDescendingHeaderStyle BackColor=”#6F8DAE” />
<asp:BoundField HeaderText=”Name” ShowHeader=”true” DataField=”Name” />

<asp:BoundField HeaderText=”Age” ShowHeader=”true” DataField=”Age” />

<asp:BoundField HeaderText=”Gender” ShowHeader=”true” DataField=”Gender” />

<asp:BoundField HeaderText=”DOB” ShowHeader=”true” DataField=”DOB” />
            <p>No record found.</p>

Now, I have a method for setting datasource to this gridview.

private DataSet MockResult(bool addrows)
DataTable dt = new DataTable(“User Information”);
DataColumn c1 = new DataColumn(“Name”);
DataColumn c2 = new DataColumn(“Age”);
DataColumn c3 = new DataColumn(“Gender”);
DataColumn c4 = new DataColumn(“DOB”);

if (addrows)
for (int i = 0; i < 1000; i++)
DataRow r = dt.NewRow();
r[c1] = “Name” + i;
r[c2] = “Age” + i;
r[c3] = “Gender” + i;
r[c4] = DateTime.Now.ToShortDateString();


DataSet ds = new DataSet();

return ds;

Now, I am setting the datasource for this gridview as shown below. The key thing here is,  do not set null value to the gridview datasource.  Even if there is no rows,  make sure that you have columns defined in the datasource object.

protected void RunButton_Click(object sender, EventArgs e)

//By passing false in the method parameter, I am just generating the columns and not the rows.
UserInformationViewer.DataSource = MockResult(false);

Now, I can see the headers even if there is no data,


August 6, 2012 Posted by | ASP.NET, C#.NET | 1 Comment