views:

2322

answers:

3

I have a linkbutton that I want to call a method in the code behind. The method takes a parameter of which I need to stick in a container.dataitem. I know the container.dataitem syntax is correct because I use it in other controls. What I don't know is how to user it a parameter for a method. Upon clicking on the button, the method should be called with the container.dataitem. The method is called 'AddFriend(string username)' Below is code. Thank you!

<asp:LinkButton ID="lbAddFriend" runat="server" OnClick='<%# "AddFriend(" +((System.Data.DataRowView)Container.DataItem)["UserName"]+ ")" %>' Text="AddFriend"></asp:LinkButton></td>
A: 

You need to use a ButtonField and handle the click in RowCommand. Check the MSDN docs

 <asp:buttonfield buttontype="Link" 
                  commandname="Add" 
                  text="Add"/>

And in the code behind...

  void ContactsGridView_RowCommand(Object sender, GridViewCommandEventArgs e)
  {
    if(e.CommandName=="Add")
    {
         AddFriend(DataBinder.Eval(Container.DataItem, "Price""UserName"));
    }
  }
scottschulthess
The linkbutton is in a datalist.
A: 

I think the same thing applies to a data list, but I've been using this for a repeater in my code behind. Mayby use DataListItemEventArgs and DataListCommandEventArgs in place of the Repeater.

protected void rptUserInfo_Data(object sender, RepeaterItemEventArgs e)
{
    if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
    {
        UserInfo oUserInfo = e.Item.DataItem as UserInfo;

        LinkButton hlUser = e.Item.FindControl("hlUser") as LinkButton;
        hlUser.Text = oUserInfo.Name;
        hlUser.CommandArgument = oUserInfo.UserID + ";" + oUserInfo.uName;
        hlUser.CommandName = "User";
    }
}
public void UserArtItem_Command(Object sende, RepeaterCommandEventArgs e)
{
    if (e.CommandName == "User")
    {
        string command = e.CommandArgument.ToString();
        string[] split = command.Split(new Char[] { ';' });

        Session["ArtUserId"] = split[0];
        Session["ArtUserName"] = split[1];
        Response.Redirect("~/Author/" + split[1]);
    }
}
Tim Meers
A: 

Maybe this?

<asp:LinkButton ID="lbAddFriend" runat="server"
 Text="Add Friend" OnCommand="AddFriend"
 CommandArgument='<%# Eval("UserName").ToString() %>' />

Then in the code:

Protected Sub AddFriend(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.CommandEventArgs)
    Dim UserName As String = e.CommandArgument
    'Rest of code
End Sub
rvarcher