CODEDIGEST
Home » Articles
Search
 

Technologies
 

Sponsored links
 

CodeDigest Navigation
 

Technology News
No News Feeds available at this time.
 

Community News
No News Feeds available at this time.
 
Making GridView Row Selectable or Clickable using jQuery in ASP.Net

By Satheesh Babu
Posted On Mar 11,2010
Article Rating:
Be first to rate
this article.
No of Comments: 2
Category: ASP.Net/jQuery
Print this article.

Making GridView Row Selectable or Clickable using jQuery in ASP.Net

 

GridView control is one of the most widely used databound control in ASP.Net. Whenever there is a requirement to display data in tabular format then one can use GridView control to achieve the goal very easily.

Normally, when we want to add select/edit/delete function in GridView we normally use a button or link button control in every row to select that row. Refer the image below,

 

How to make ASP.Net GridView Row Selectable or Clickable OR highlight a GridView Row using Javascript?

 

It will be good and user friendly if make the GridView control’s row itself selectable instead of having separate buttons in every row. Also, by making GridView row selectable, we can also save some space horizontally so that we can use the space to include more columns to display in the GridView.

Refer below,

How to make ASP.Net GridView Row Selectable or Clickable OR highlight a GridView Row using Javascript?

 

Well, this can be implemented by injecting some javascript code and making the GridView rows selectable. In the client side, the GridView control will be actually rendered as HTML table control with the data being displayed in TR and TD. Hence, when i say GridView row selectable, i actually mean to change the background color to black and fore ground color to white to look like selected row.

 

To make the development easier and simple, we will use the new jQuery library instead of writing javascript code.

If you are new to jQuery, i advise you to read the below FAQ’s to have a quick understanding.

What is jQuery? How to use it in ASP.Net Pages?

How to enable jQuery intellisense in Visual Studio 2008?

How to use jQuery intellisense in an external javascript file?

 

Read the below article, to know more about jQuery library and its advantages,

Introduction to jQuery in ASP.Net and 10 Advantages to Choose jQuery

 

Moving forward, we will see how to do this using jQuery library.

Steps

1.      Open Visual Studio 2008 and create a new Asp.Net website project. Add a new Sql Express database in App_Data folder of your solution.

Note

To add new table, just right click the added database and select “Open” to open your database in Server Explorer. Now, create a table called Users with the necessary columns using the “Server Explorer”.

2.      Drag a GridView control from data tab of visual studio and name it as gvUsers.

3.      Include new DataBound columns to display the columns in the GridView control. I have included 3 columns for First name, Last name and Email. Set the primary key field to DataKeyNames property of the GridView control to identify the row user has selected. Refer below,

<asp:GridView ID="gvUsers" runat="server" AutoGenerateColumns="False"

            DataKeyNames="UserID">

                    <Columns>                      

                        <asp:BoundField DataField="FirstName" HeaderText="First Name" ReadOnly="True" />

                        <asp:BoundField DataField="LastName" HeaderText="Last Name" ReadOnly="True" />     

                         <asp:BoundField DataField="Email" HeaderText="Email" ReadOnly="True" />                             

                    </Columns>

                     <FooterStyle BackColor="White" ForeColor="#330099" />

                    <RowStyle BackColor="White" ForeColor="#330099" />

                    <SelectedRowStyle BackColor="#FFCC66" Font-Bold="True" ForeColor="#663399" />

                    <PagerStyle BackColor="#FFFFCC" ForeColor="#330099" HorizontalAlign="Center" />

                    <HeaderStyle BackColor="#F06300" Font-Bold="True" ForeColor="#FFFFCC" />

     </asp:GridView>

 

4.      Now, bind the GridView control from the codebehind by fetching the data from users table.

protected void Page_Load(object sender, EventArgs e)

    {

 

        if (!IsPostBack)

            BindUsers();

    }

    public void BindUsers()

    {

        DataTable dt = GetUsersForModeration();

        gvUsers.DataSource = dt;

        gvUsers.DataBind();

    }

    public DataTable GetUsersForModeration()

    {

        SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["Sql"].ConnectionString);

        con.Open();

        SqlCommand com = new SqlCommand("SP_GetUsersForModeration", con);

        com.CommandType = CommandType.StoredProcedure;

        SqlDataAdapter ada = new SqlDataAdapter(com);

        DataSet ds = new DataSet();

        ada.Fill(ds);

        return ds.Tables[0];

    }

 

The connection string will look like,

<connectionStrings>

              <add name="Sql" connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True;User Instance=True;"/>

       </connectionStrings>

 

Execute the page. You can see the Users data displayed in the GridView.

5.      Since, we are not displaying the primary key field to the users in GridView control we need to send the key value associated with every row to the client so that we can identify the clicked row from client side. To do this, we will add id property to every row of GridView control except the header and assign the primary key field value as value to the id property.

protected void gvUsers_RowDataBound(object sender, GridViewRowEventArgs e)

    {       

        if (e.Row.RowType == DataControlRowType.DataRow)

        {

            string key = gvUsers.DataKeys[e.Row.RowIndex].Value.ToString();          

            e.Row.Attributes.Add("id", key);

        }

    }

 




Now, the rendered HTML table will include id property to every TR tag. Refer below,

<table cellspacing="0" rules="all" border="1" id="gvUsers" style="border-collapse:collapse;">

              <tr style="color:#FFFFCC;background-color:#F06300;font-weight:bold;">

                     <th scope="col">First Name</th><th scope="col">Last Name</th><th scope="col">Email</th>

              </tr><tr id="1" style="color:#330099;background-color:White;">

                     <td>Satheesh</td><td>babu</td><td>satheesh@gmail.com</td>

              </tr><tr id="2" style="color:#330099;background-color:White;">

                     <td>vadivel</td><td>m</td><td>vadi@gmail.com</td>

              </tr><tr id="3" style="color:#330099;background-color:White;">

                     <td>John</td><td>m</td><td>John@gmail.com</td>

              </tr><tr id="4" style="color:#330099;background-color:White;">

                     <td>Peter</td><td>m</td><td>Peter@gmail.com</td>

              </tr><tr id="5" style="color:#330099;background-color:White;">

                     <td>Kavi</td><td>m</td><td>Kavi@gmail.com</td>

              </tr><tr id="6" style="color:#330099;background-color:White;">

                     <td>Freddy</td><td>m</td><td>Freddy@gmail.com</td>

              </tr><tr id="7" style="color:#330099;background-color:White;">

                     <td>martin</td><td>m</td><td>martin@gmail.com</td>

              </tr>

       </table>

 

6.      Next, we will integrate the jquery library and make the GridView row(TR tag) selectable. Refer the FAQs above to integrate the jQuery library.

7.      To make every row selectable, we can add a click event to every TR except header.  Refer the below code,

       <script src="_scripts/jquery-1.4.1.min.js" type="text/javascript"></script>

<script type="text/javascript">

    $(function() {

 

        $('#<%=gvUsers.ClientID%> tr[id]').click(function() {

            $('#<%=gvUsers.ClientID%> tr[id]').css({ "background-color": "White", "color": "Black" });

            $(this).css({ "background-color": "Black", "color": "White" });          

        });

     

        $('#<%=gvUsers.ClientID%> tr[id]').mouseover(function() {

            $(this).css({ cursor: "hand", cursor: "pointer" });

        });

 

    });

</script>

               

The selector expression tr[id] will ensure the click event is added to only datarows since we have added id attribute to only data rows from code behind(step 5). Execute the page and you can see the selectable gridview in action.

8.  Now, we need to send the selected rows identity (primary key) to the codebehind so that it can be selected to complete its action. To do this, we will add a hidden field(hdnEmailID) to the aspx page and fill it with the identity of the selected row from jquery script. Update the above jquery code to set the hidden field with the identity key value. Refer the bolded code below,

<script type="text/javascript">

    $(function() {      

 

        $('#<%=gvUsers.ClientID%> tr[id]').click(function() {

            $('#<%=gvUsers.ClientID%> tr[id]').css({ "background-color": "White", "color": "Black" });

            $(this).css({ "background-color": "Black", "color": "White" });

            $('#hdnEmailID').val($(this).attr("id"));

        });

 

        $('#<%=gvUsers.ClientID%> tr[id]').mouseover(function() {

            $(this).css({ cursor: "hand", cursor: "pointer" });

        });

     

    });

</script>

<INPUT id="hdnEmailID" type="hidden" value="0" runat="server" >

 

You can access the hidden field value in codebehind complete the action required in the codebehind file. Refer the button click events below,

protected void btnSelect_Click(object sender, EventArgs e)

    {

        Response.Write(hdnEmailID.Value);

        //Do your action

    }

    protected void btnDelete_Click(object sender, EventArgs e)

    {

        Response.Write(hdnEmailID.Value);

        //Do your action

      hdnEmailID.Value = "0";

    }

 

Retaining Selection after a Select Action

When we do a select action i.e. clicking select button, it will be good if we retain the selected row after the postback to know the selected row. The below code does that. Refer the bolded code.

<script src="_scripts/jquery-1.4.1.min.js" type="text/javascript"></script>

<script type="text/javascript">

    $(function() {

 

        var RowID = $('#hdnEmailID').val();

        if (RowID != "0") {

            $('#<%=gvUsers.ClientID%> tr[id=' + RowID + ']').css({ "background-color": "Black", "color": "White" });

        }

 

        $('#<%=gvUsers.ClientID%> tr[id]').click(function() {

            $('#<%=gvUsers.ClientID%> tr[id]').css({ "background-color": "White", "color": "Black" });

            $(this).css({ "background-color": "Black", "color": "White" });

            $('#hdnEmailID').val($(this).attr("id"));

        });

 

        $('#<%=gvUsers.ClientID%> tr[id]').mouseover(function() {

            $(this).css({ cursor: "hand", cursor: "pointer" });

        });

 

    });

</script>

 

Note:

Set the hidden field to 0 in delete action after deleting the row.

 

Downloads

Download Source 

Conclusion

The introduction of jquery really made our life easier by making the clientside DOM manipulations simpler. Thus, by using jquery and ASP.Net Gridview control we have made the gridview control as a more sophisticated control by making its row selectable.

Download the source attached with the article and see it in action.

Happy coding!!

 

 

Similar Articles
You can contribute to CodeDiget.Com:
Donate to CodeDigest.com
Article Feedback
Comments
Very helpful indeed!
By far the most detailed explanation on this subject :)
Thanks
nice
thank you
i love you man ^_^