Earlier today I was just playing around with SharePoint 2010 and thought I should do a simple task with SPGridView, that is to display the data and show an appropriate image in the “Status” column instead of the text. Hmm, sounds quite simple doesn’t it! But no, it turned into a misery. Well, when I started it was quite natural to use the OnRowDataBound event on that to capture the data and do some modifications with the controls (I was using TemplateFields in the SPGridView by the way), so I did that and I tried doing things like e.Row.FindControl(“xyz”), e.Row.Cells and using RowIndex property which was returning -1 where e refers to an object of GridViewRowEventArgs and there was nothing to get over there. It was nulls all around!
So here’s a sample of the code in the visual webpart that I was writing:-
<SharePoint:SPGridView ID=”spGvWorkOrders” runat=”server” >
<asp:Label ID=”lbl_workOrderId” Text='<% # Bind(“Id”) %>’ runat=”server”></asp:Label>
<asp:Label ID=”lbl_workOrderTitle” runat=”server” Text='<% # Bind(“Title”) %>’ ></asp:Label>
<asp:Image ID=”img_status” Width=”10px” ImageUrl='<% #StatusToImage(“\””+ Eval(“Status”)+”\””) %>’ runat=”server” />
And here is the function:-
protected string StatusToImage(string status)
if ( ( rowcount++ % 2) == 0)
Notice that I had been using the Bind function earlier but when I tried using it to send the value to StatusToImage function it did not work. Eval is the better option anyway in case you’re just interesting in displaying the data.
So what I did was that instead of using the event I just put the function call inside the ascx code so that whenever a row is created that function is called with the value of Status from the Data Source and with that value sent to a function, we can return back a string to give the path to the image file. The syntax however, is quite tricky and it took me a while to figure that out correctly but it worked in the end. Hope it will save you some time though!