Skip to content

Have GridView Highlight Last Inserted Record in ASP.NET 2.0

Updated: at 11:17 PM

Introduction

A question that frequently comes up in the asp.net forums is how to have a gridview show the the last record added highlighted. This articles gives a technique for doing this. It only works with SqlServer but could could be modified for other databases.

What It Looks Like Running

After pressing the insert button on the screen shot below, the bottom line was actually added and it is automatically highlighted. This is in a nutshell, what the code listed below and this article discusses.

The Code

In order to run the code below, you must first set up Membership. The simplest way to do this is to simply add to your web.config a very small section enabling RoleManager. This will automatically create the membership database in sqlexpress. You should probably add a couple users just so your gridview is not empty from the start. The code you need to add to an empty asp.net 2.0 web site project is as follows (put it in the <System.Web> section).

<roleManager enabled="true"></roleManager>

Once you have done that, you can copy the code below to a new web page and simply run it.

Briefly, the way the code works is that when a row is inserted into the database the sqldatasource's Inserted event is called. In this event, we take a look at the return parameter which comes from the sql:

InsertCommand="INSERT INTO [Names] ([name]) VALUES (@name);SELECT @NewID = Scope_Identity()"

NewId is actually a return parameter, so we can get that back in the inserted event. Once we get the value back, we store it in viewstate so that on the upcoming page_prerender, we can check and see which row has that id in it, and then highlight that row. The reason we do it in prerender and not load is because the inserted event is processed after load and it would not work if we put it there.

So, here is the code! Good luck.

<%@ Page Language=”C#” %>

<!DOCTYPE html PUBLIC-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd>

<script runat=”server>

<span class="rem">// simple table named: Names. Two columns:  id int, name varchar(64)</span>

<span class="kwrd">protected</span> <span class="kwrd">void</span> ButtonInsert_Click(<span class="kwrd">object</span> sender, EventArgs e)
{      
    SqlDataSource1.InsertParameters[<span class="str">&quot;name&quot;</span>].DefaultValue = DateTime.Now.ToString();
    <span class="kwrd">int</span> numInserted = SqlDataSource1.Insert();
    GridView1.DataBind();
}

<span class="kwrd">protected</span> <span class="kwrd">void</span> SqlDataSource1_Inserted(<span class="kwrd">object</span> sender, SqlDataSourceStatusEventArgs e)
{
    <span class="kwrd">object</span> newId = e.Command.Parameters[<span class="str">&quot;@NewId&quot;</span>].Value;
    ViewState[<span class="str">&quot;NewId&quot;</span>] = Convert.ToInt32(newId);
}

<span class="kwrd">protected</span> <span class="kwrd">void</span> Page_PreRender(<span class="kwrd">object</span> sender, EventArgs e)
{
    <span class="kwrd">string</span> newIdLast = <span class="kwrd">string</span>.Empty;
    <span class="kwrd">if</span> (ViewState[<span class="str">&quot;NewId&quot;</span>] != <span class="kwrd">null</span>)
    {
        <span class="kwrd">int</span> newId = (<span class="kwrd">int</span>)ViewState[<span class="str">&quot;NewId&quot;</span>];
        newIdLast = newId.ToString();
        <span class="kwrd">int</span> rowCnt = 0;
        <span class="kwrd">foreach</span> (GridViewRow row <span class="kwrd">in</span> GridView1.Rows)
        {
           <span class="kwrd">string</span> newIdText = row.Cells[1].Text;
            <span class="kwrd">if</span> (newIdText.Equals(newIdLast))
            {
                <span class="rem">//GridView1.EditIndex = rowCnt;</span>
                <span class="rem">//GridView1.SelectedIndex = rowCnt;</span>
                row.Attributes.Add(“bgcolor”, “Gray”);
                <span class="kwrd">break</span>;
            }
            rowCnt++;
        }
    }
}

</script>

<html xmlns=”http://www.w3.org/1999/xhtml> <head id=”Head1? runat=”server> <title>Untitled Page</title> </head> <body> <form id=”form1? runat=”server> <div> <h2>Example of GridView that shows highlighted last inserted row</h2> <br /> <asp:GridView ID=”GridView1? runat=”serverAutoGenerateColumns=”FalseDataKeyNames=”idDataSourceID=”SqlDataSource1? > <Columns> <asp:CommandField ShowEditButton=”TrueShowDeleteButton=”True/> <asp:BoundField DataField=”idHeaderText=”idInsertVisible=”FalseReadOnly=”TrueSortExpression=”id/> <asp:BoundField DataField=”nameHeaderText=”nameSortExpression=”name/> </Columns> </asp:GridView> <asp:SqlDataSource ID=”SqlDataSource1? runat=”serverConnectionString=”&lt;%$ ConnectionStrings:ConnectionString %&gt;“ DeleteCommand=”DELETE FROM [Names] WHERE [id] = @idInsertCommand=”INSERT INTO [Names] ([name]) VALUES (@name);SELECT @NewID = Scope_Identity()”

      <span class="attr">SelectCommand</span>=”<span class="attr">SELECT</span> [<span class="attr">id</span>], [<span class="attr">name</span>] <span class="attr">FROM</span> [<span class="attr">Names</span>]“ <span class="attr">UpdateCommand</span>=”<span class="attr">UPDATE</span> [<span class="attr">Names</span>] <span class="attr">SET</span> [<span class="attr">name</span>] = @<span class="attr">name</span> <span class="attr">WHERE</span> [<span class="attr">id</span>] = @<span class="attr">id</span>” <span class="attr">OnInserted</span>=”<span class="attr">SqlDataSource1_Inserted</span>”<span class="kwrd">&gt;</span>
        <span class="kwrd">&lt;</span><span class="html">DeleteParameters</span><span class="kwrd">&gt;</span>
            <span class="kwrd">&lt;</span><span class="html">asp:Parameter</span> <span class="attr">Name</span>=”<span class="attr">id</span>” <span class="attr">Type</span>=”<span class="attr">Int32</span>? <span class="kwrd">/&gt;</span>
        <span class="kwrd">&lt;/</span><span class="html">DeleteParameters</span><span class="kwrd">&gt;</span>
        <span class="kwrd">&lt;</span><span class="html">UpdateParameters</span><span class="kwrd">&gt;</span>
            <span class="kwrd">&lt;</span><span class="html">asp:Parameter</span> <span class="attr">Name</span>=”<span class="attr">name</span>” <span class="attr">Type</span>=”<span class="attr">String</span>” <span class="kwrd">/&gt;</span>
            <span class="kwrd">&lt;</span><span class="html">asp:Parameter</span> <span class="attr">Name</span>=”<span class="attr">id</span>” <span class="attr">Type</span>=”<span class="attr">Int32</span>? <span class="kwrd">/&gt;</span>
        <span class="kwrd">&lt;/</span><span class="html">UpdateParameters</span><span class="kwrd">&gt;</span>
        <span class="kwrd">&lt;</span><span class="html">InsertParameters</span><span class="kwrd">&gt;</span>
            <span class="kwrd">&lt;</span><span class="html">asp:Parameter</span> <span class="attr">Name</span>=”<span class="attr">name</span>” <span class="attr">Type</span>=”<span class="attr">String</span>” <span class="kwrd">/&gt;</span>
           <span class="kwrd">&lt;</span><span class="html">asp:Parameter</span> <span class="attr">Direction</span>=<span class="attr">Output</span> <span class="attr">Name</span>=”<span class="attr">NewId</span>” <span class="attr">Size</span>=<span class="attr">4</span> <span class="attr">Type</span>=<span class="attr">Int16</span> <span class="kwrd">/&gt;</span>
        <span class="kwrd">&lt;/</span><span class="html">InsertParameters</span><span class="kwrd">&gt;</span>
    <span class="kwrd">&lt;/</span><span class="html">asp:SqlDataSource</span><span class="kwrd">&gt;</span>
    <span class="kwrd">&lt;</span><span class="html">br</span> <span class="kwrd">/&gt;</span>
    <span class="kwrd">&lt;</span><span class="html">br</span> <span class="kwrd">/&gt;</span>
    <span class="attr">&amp;nbsp;</span><span class="kwrd">&lt;</span><span class="html">asp:Button</span> <span class="attr">ID</span>=”<span class="attr">ButtonInsert</span>” <span class="attr">runat</span>=”<span class="attr">server</span>” <span class="attr">OnClick</span>=”<span class="attr">ButtonInsert_Click</span>” <span class="attr">Text</span>=”<span class="attr">Insert</span> <span class="attr">Record</span>” <span class="kwrd">/&gt;&lt;/</span><span class="html">div</span><span class="kwrd">&gt;</span>
<span class="kwrd">&lt;/</span><span class="html">form</span><span class="kwrd">&gt;</span>

</body> </html>

About the Author

Peter Kellner currently works as an asp.net enterprise consultant at http://www.73rdstreet.com. During the past year, Peter Kellner has authored four MSDN articles dealing with Membership and Profiles. He maintains a blog with more articles at https://peterkellner.net.