mha.dk

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"
OnRowCommand="GridView1_RowCommand">
    <Columns>
        <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">
            <ItemTemplate>
                <%# CalculatePrice(Eval("DefaultPrice"), Eval("ItemID"))%>
            </ItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="Antal">
            <ItemTemplate>
                <asp:TextBox ID="txtQuantity" runat="server" Style="text-align: right" Width="50">1</asp:TextBox>
            </ItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="Discount">
            <ItemTemplate>
                <%# ShowProductDiscount(Eval("ItemID"))%>
            </ItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField>
            <ItemTemplate>
                <asp:ImageButton ID="ImageButton1" CommandArgument='<%#Container.DataItemIndex %>'
                    CommandName="AddToBasket" runat="server" ToolTip="Klik for tilføje til kurv"
                    ImageUrl="~/Images/icon_addtobasket.gif" />
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>

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:


DEVELOPER TOOLS, COMMERCIAL


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

EditPlus
http://www.editplus.com/
The best ASCII text editor for Windows!

EMS SQL Manager 2008 for SQL Server
http://sqlmanager.net/products/mssql/manager
If you’re using MS SQL Server as your storage engine, you simply can’t live without this one!!

ReSharper 4.5
http://www.jetbrains.com/resharper/
The #1 plug-in for Visual Studio

TotalCommander
http://www.ghisler.com/
File handling for professionals (no more Windows Explorer, please!!)


DEVELOPER TOOLS, FREE


Fiddler2
http://www.fiddler2.com/fiddler2/
If you’re working with AJAX or JSON, this is a “must have”

NUnit
http://www.nunit.org/index.php
Remember: Testing is goooood :)

TortoiseSVN / SubVersion
http://tortoisesvn.tigris.org/
http://www.visualsvn.com/server
Of course we all use SubVersion, right ?!

LINQPad
http://www.linqpad.net/
Awesome LINQ utility .. and for about $20 you even get autocomplete

Reflector
http://www.red-gate.com/products/reflector/
Explore, browse, and analyze .NET assemblies (it’s great fun :-)

WinMerge
http://winmerge.org/
Beats the built-in “diff” any day!

Opera + Safari (ThinDownload)
http://www.thindownload.com/
No need to install Opera/Safari, simply use a “thin” install

Chrome
http://www.google.com/chrome
Testing in multiple browsers is a lot of fun, ehhh – not really!

FireFox
http://www.mozilla.com/firefox/
The #1 browser for developers (and other ‘cool’ people! :)

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

    Xmarks
    Web Developer
    Firebug
    YSlow
    Mouse Gestures Redox
    PDF Download
    Tab Kit
    Abduction!   
    Window Resizer
    ColorZilla

Consolas Font Pack for Visual Studio
http://www.microsoft.com/downloads/details.aspx?familyid=22e69ae4-7e40-4807-8a86-b3d36fab68d3&displaylang=en
I just have to read all my code with this font

ASP.NET MVC 1.0
http://www.asp.net/mvc/
You might as well forget about those Web Forms!! :-)

ViewstateDecoder
http://www.pluralsight.com/community/media/p/51688.aspx
..but if you’re still using Web Forms, this one might come in handy

Virtual PC 2007 SP1
http://www.microsoft.com/downloads/details.aspx?familyid=28C97D22-6EB8-4A09-A7F7-F6C7A1F000B5&displaylang=en
I mostly use Hyper-V machines, but this one will run on my laptop

Windows Live Writer
http://download.live.com/writer
Really makes it SO much easier to blog (works with BlogEngine.NET)


PRODUCTIVITY TOOLS, COMMERCIAL


UltraMon
http://www.realtimesoft.com/ultramon/
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!!

WinRAR
http://www.rarlab.com/
The best packer/zipper on the marked

CuteFTP
http://www.globalscape.com/
Lot’s of free (and actually good) FTP programs out there, but CuteFTP rules them all


PRODUCTIVITY TOOLS, FREE


Corbian Backup
http://www.educ.umu.se/~cobian/cobianbackup.htm
Free and really awesome backup utility, will backup to nearly every storage device you can think of.

Acrobat Reader http://www.adobe.com/dk/products/reader/
Fox Reader http://www.foxitsoftware.com/pdf/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! :-)

FontViewer
http://fontviewer.net/
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)

Launchy
http://www.launchy.net/
The fastest way to launch programs (and doing other cool stuff)

DropBox
https://www.getdropbox.com/home
THE tool to use when you’re sharing files with your friends, clients etc – simply rocks!

CutePDF Writer
http://www.cutepdf.com/Products/CutePDF/writer.asp
No need to buy Acrobat to make a PDF file

FeedDemon
http://www.feeddemon.com/
The #1 RSS reader (I don’t like web based readers!)

TurboTop
http://www.savardsoftware.com/turbotop/
Hey window .. stay in front, I say!!

XnView
http://www.xnview.com/
Exactly how an image viewer/browser should work!!

Terminals
http://www.codeplex.com/Terminals
Secure, multi tab terminal services/remote desktop client – nice!

Keepassportable
http://portableapps.com/apps/utilities/keepass_portable
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 http://patorjk.com/software/taag - which one do you use?! :-)