Let's say you have a GridView, and you want to have a hyperlink in each row that will supply parameters to a url based on some values in the selected row. We can use one of the two controls to accomplish this task - a HyperLink or a LinkButton.
This is how you do it with a HyperLnk control.
First, we build a GridView:
<asp:GridView ID="gv1" runat="server" BorderWidth="0" AutoGenerateColumns="False" OnRowDataBound="gv1_RowDataBound"
ShowHeader="False">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:HyperLink ID="myID" runat="server"
Text = '<%# DataBinder.Eval(Container, "DataItem.myField") %>'
/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
The text that appears in the only column will reflect the value of "DataItem.myField" that you assigned to it.
Next, you need to create an OnRowDataBound event. In the method that responds to this event you use the following code:
protected void gv1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
HyperLink hl = (HyperLink)e.Row.FindControl("myID");
if (hl != null)
{
MyDataClass mdc = (MyDataClass)e.Row.DataItem;
hl.NavigateUrl = "?myParam=" + mfc.SomeFieldName;
}
}
}
I assume that the data source to the GridView is a list of instances of MyDataClass. In the code above, the resulting url will point to the same page and supply a parameter called 'myParam'. The parameter value corresponds to the value of SomeFieldName property.
The resulting call to the same page will use the GET method.
If you want to use the POST method, you need to use the LinkButton control.
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="lbt1" runat="server" OnCommand="lbt1_Command" CommandArgument="<%# Container.DisplayIndex %>"><%# Eval("Title") %></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
The CommandArgument property will hold a row index.
When we used the Hyperlink control, we added request parameters using the RowDataBound event method. This time, we are going to use the LinkButton.OnCommand method.
First, we need to use the GridView DataKeyNames property. Its value will contain the names of the DataSet field names that we want to use as request parameters on the LinkButton click. In our example:
DataKeyNames="FolderName,Title"
Now, in the Command method we'll use the following code to get the values of FolderName and Title fields.
int index = Convert.ToInt16(e.CommandArgument);
IOrderedDictionary allKeysDictionary = gv1.DataKeys[index].Values;
string folderName =allKeysDictionary["FolderName"].ToString();
string title = allKeysDictionary["Title"].ToString();
Some information gleaned from this page has been of great help.