Friday, April 13, 2007

Nested Data controls: Passing field values to code behind with LinkButton*

Friday, April 13, 2007 8:52:10 PM (GMT Standard Time, UTC+00:00)

Sometimes coding can be SOO frustrating, but other times, it is SOO cool!! I think one of the main things that I thrive on when I have a problem (with coding) is that "this is coding, there MUST be a way to get this done! A different way to skin the 'proverbial' cat!" Then... after a while, I usually get it done!

This time the problem was with asp:LinkButton (embedded in a DataList control ItemTemplate). Essentially what I wanted to to was to pass a field (abc_id) from the current DataList item, into the code-behind when the user clicked the LinkButton. Ideally, I would have liked to do the following (in theory):

<asp:LinkButton ID="Button1" runat="server" Text="ABC" OnClick="b_Click('Eval("abc_id")',Nothing)"></asp:LinkButton>

Then.. in the code-behind have:

Protected Sub b_Click(ByVal sender As Object, ByVal e As System.EventArgs)
    'Do whatever... with the received "abc_id" which will be in the "sender" object
End Sub

The problem with this however is that you get the error, "'AddressOf' operand must be the name of a method (without parentheses)." i.e. you can't have the "('Eval("abc_id")',Nothing)" after the b_click or even just the "()"! Sooo, what to do now?

Well luckily on this site, the author lead me to a quite lovely solution to the problem that would enable you to pass field values nicely to the code-behind. The trick is to use the Command properties (e.g. OnCommand, CommandName, CommandArgument) of the LinkButton! So.. if I modify my original code above we'll now have:

<asp:LinkButton ID="Button1" runat="server" Text="ABC" OnCommand="b_Click" CommandArgument='<%#Eval("abc_id")%>'></asp:LinkButton>

And in the code-behind:

Protected Sub b_Click(ByVal sender As Object, ByVal Args As CommandEventArgs)
    Dim abc_id as string = Args.CommandArgument
    'Do whatever else... Oh and the "sender.id" and "Args.CommandName" can also be used.
End Sub

Nifty huh? I find this technique so useful in dealing with data controls (like DataList, FormViews and Repeaters) when they've been nested.

Related posts:
Select a random row in MS SQL...
Regular expressions
VS2005, ASP.NET 2 & DLLs, DLLs..
MS's ASP.NET and.. PHP
2-way databinding cascading drop down lists within a FormView
ApplicationName Property when customising providers

Comments are closed.