Random thoughts of wisdom - the personal blog of Michael Holm Andersen

GridView and the RowCommand event

The GridView is a powerful control, however dealing with multiple different column types in the RowCommand event still is a little messy! – I’ve put together a small sample which utilize the most common column types.

I have a GridView which looks like this:

<asp:GridView ID="GridView1" runat="server" AllowSorting="True"
    AutoGenerateColumns="False" DataKeyNames="ItemID" DataSourceID="LinqDataSource1"
        <asp:BoundField DataField="ItemID" HeaderText="ItemID" Visible="false" InsertVisible="False"
            ReadOnly="True" SortExpression="ItemID" />
        <asp:HyperLinkField DataTextField="Name" HeaderText="Produkt" DataNavigateUrlFields="ItemID"
            DataNavigateUrlFormatString="ProductView.aspx?id={0}" SortExpression="Name" />
        <asp:BoundField DataField="ItemNo" HeaderText="Varenr." SortExpression="ItemNo" />
        <asp:TemplateField HeaderText="Pris u/moms" SortExpression="DefaultPrice">
                <%# CalculatePrice(Eval("DefaultPrice"), Eval("ItemID"))%>
        <asp:TemplateField HeaderText="Antal">
                <asp:TextBox ID="txtQuantity" runat="server" Style="text-align: right" Width="50">1</asp:TextBox>
        <asp:TemplateField HeaderText="Discount">
                <%# ShowProductDiscount(Eval("ItemID"))%>
                <asp:ImageButton ID="ImageButton1" CommandArgument='<%#Container.DataItemIndex %>'
                    CommandName="AddToBasket" runat="server" ToolTip="Klik for tilføje til kurv"
                    ImageUrl="~/Images/icon_addtobasket.gif" />

Note: I have a couple of public methods which calculates the price and discount, these methods are omitted in the below code (to simply things!).

In the RowCommand (code-behind) I have this:

protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
       if (e.CommandName == "AddToBasket")
           // get the index for the row which fired event
           int index = Convert.ToInt32(e.CommandArgument);

           // get primary key value from gridview DataKeys collection
           int ItemID = Convert.ToInt32(this.GridView1.DataKeys[index].Value);

           // get the current GridViewRow
           GridViewRow row = (GridViewRow)((Control)e.CommandSource).Parent.Parent;

           // get the HyperLinkField column
           HyperLink hyper = row.Cells[1].Controls[0] as HyperLink;
           if (hyper != null)
               string LinkText = hyper.Text;

           // get the TextBox column (Find control, cast to TextBox and convert .Text to short)
           short Quantity = short.Parse(((TextBox)GridView1.Rows[index].FindControl("txtQuantity")).Text);

           // get Price (CalculatePrice() return a string which is converted to a DataBoundLiteralControl)
           DataBoundLiteralControl lit = row.Cells[3].Controls[0] as DataBoundLiteralControl; 
           if (lit != null)
               float Price = float.Parse(lit.Text);


There you have it! – The ‘trick’ is to get your hands on the GridViewRow and then cast the various row.Cells[N] to the proper type (like above with the HyperLinkField), this technique works just as well with buttonfield and checkboxfield columns.

If don’t want to “spend time” pulling out the GridViewRow, you can also take the slightly more ‘directly’ approach (as I’ve done above with the TextBox column), where I (instead of using ‘row’) uses the GridView1.Rows[index].FindControl syntax instead (I prefer pulling out the GridViewRow, though).

That’s it! – Have fun poking around that RowCommand event! :-)

So Long, and Thanks for All the Fish

As many of you may already know, on the 1st of September I'm leaving the Web Development Team at Telenor and begins a new career at Gateway Distribution as a .NET developer / system architect.

It’s been a great 2½ years at Telenor, and I’ve really enjoyed working together with all the talented and wonderful people, both inside my team and outside (Custom Relations, eBusiness, DataWare House, etc.)

I’ll like to thank you all, and wish everyone the best of luck and good wishes - It's been really fun and I'm sure we'll meet online - until then - So Long, and Thanks for All the Fish!

OCZ Vertex SSD Benchmark

René from work is currently testing out how much SSD will speed up the compilation process. In order to compare the SSD he is testing, I gave it at go at my Vertex SSD and the numbers it quite pleasing :)

The test is “raw” I/O read and write and does not test the access time of the SSD, which actually is the most interesting property of an SSD disk compared to a normal 7200RPM harddrive.

If you want to test your own SSD / Harddrive, you can download the ATTO Disk Benchmark from the TechPowerUp website.

My Toolbox

As I’m planning to switch to Windows7 within a month or so, I’m faced with the ever returning problem of re-installing my system (dammit!)

To help me remember which programs to install, and to answer some of the questions asked back in May at the AANUG “tool night” meeting, here is a – more of less – complete list of my Developer and Productivity toolbox:


Visual Studio 2008
This one hardy needs any introduction :-)

The best ASCII text editor for Windows!

EMS SQL Manager 2008 for SQL Server
If you’re using MS SQL Server as your storage engine, you simply can’t live without this one!!

ReSharper 4.5
The #1 plug-in for Visual Studio

File handling for professionals (no more Windows Explorer, please!!)


If you’re working with AJAX or JSON, this is a “must have”

Remember: Testing is goooood :)

TortoiseSVN / SubVersion
Of course we all use SubVersion, right ?!

Awesome LINQ utility .. and for about $20 you even get autocomplete

Explore, browse, and analyze .NET assemblies (it’s great fun :-)

Beats the built-in “diff” any day!

Opera + Safari (ThinDownload)
No need to install Opera/Safari, simply use a “thin” install

Testing in multiple browsers is a lot of fun, ehhh – not really!

The #1 browser for developers (and other ‘cool’ people! :)

..and my FireFox add-on's (use Google to find download links!):

    Web Developer
    Mouse Gestures Redox
    PDF Download
    Tab Kit
    Window Resizer

Consolas Font Pack for Visual Studio
I just have to read all my code with this font

You might as well forget about those Web Forms!! :-)

..but if you’re still using Web Forms, this one might come in handy

Virtual PC 2007 SP1
I mostly use Hyper-V machines, but this one will run on my laptop

Windows Live Writer
Really makes it SO much easier to blog (works with BlogEngine.NET)


If you’re not using multiple monitors, you’re missing out .. and if you’re running multiple monitors without UltraMon .. you’re missing out too!!

The best packer/zipper on the marked

Lot’s of free (and actually good) FTP programs out there, but CuteFTP rules them all


Corbian Backup
Free and really awesome backup utility, will backup to nearly every storage device you can think of.

Acrobat Reader
Fox Reader
I’m using both, but actually prefers Acrobat Reader as it renders output better than Fox (and with a SSD there’s no waiting for programs to launch anymore .. magic! :-)

When doing webdesign stuff (still does that from time to time – using Photoshop, of course!), it’s nice to be able to view all the fonts on monitor 2)

The fastest way to launch programs (and doing other cool stuff)

THE tool to use when you’re sharing files with your friends, clients etc – simply rocks!

CutePDF Writer
No need to buy Acrobat to make a PDF file

The #1 RSS reader (I don’t like web based readers!)

Hey window .. stay in front, I say!!

Exactly how an image viewer/browser should work!!

Secure, multi tab terminal services/remote desktop client – nice!

If you’re like me .. you have (way too many) username/password combinations to remember – store them all in a secure, safe AND portable place

ASCII Text Generator

ASCII art / text is so COOL (also looks nice as comments in your C# code!!) - I use - which one do you use?! :-)