Introduction:
GridView is one of the most widely used data bound controls in
the ASP.NET 2.0 framework. GridView being a template control allows other
controls to be added in it in different columns. These columns are hyperlink,
select, delete, update and many other types of columns. In this article I will
show you that how you can make a GridView row clickable. This will allow you to
click anywhere on the row and perform the task that you wish to perform.
Populating the GridView Control:
The first task at hand is to populate the GridView control
with some data. Take a look at the code below which populates the GridView
control.
|
private
void
BindData() {
SqlConnection myConnection =
new
SqlConnection(ConnectionString);
SqlCommand
myCommand = new
SqlCommand("SELECT
* FROM Users",
myConnection);
SqlDataAdapter ad =
new
SqlDataAdapter(myCommand);
DataSet
ds = new
DataSet();
ad.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
} |
Making the GridView Row Clickable:
After the GridView is populated with the data the next task is
to make the row clickable. This is pretty straight forward task and can be
achieved by using few lines of code. The most important thing to remember is
that you have to attach the button click attribute inside the
GridView_RowDataBound event. The Row_DataBound event is fired whenever a row is
bound to the GridView control. Check out the code below:
|
protected
void
GridView1_RowDataBound(object
sender, GridViewRowEventArgs
e) {
string
alertBox = "alert('";
if
(e.Row.RowType == DataControlRowType.DataRow)
{
alertBox += e.Row.RowIndex;
alertBox +=
"')";
e.Row.Attributes.Add("onclick",
alertBox);
}
} |
As, you can see from the above code that all I am doing is
attaching the onclick attribute to the GridViewRow. The onclick event will pop
up an alert box which will display the current RowIndex of the GridViewRow.
Conclusion:
In this article you learned that how you can make a complete
row editable. Making a row editable gives you the ability to click anywhere on
the row and process the information. You can even change the color of the row
when the row is clicked.
I hope you liked the article, happy coding!