Buttons and repeater control

2019-07-29 01:20发布

问题:

I am using ASP.NET, C#, Sql Server 2005 for my project and I'm using the repeater control to form a table of users that are a member of a site and a button next to each user so that they can be added to your friends list. I have everything set up except I dont know how to get the specific info of each row after a button click. I mean,

How to send a friend request to a person whose username is displayed besides the button? or How to access the the displayed username besides the button so that I can use it for my code?

My Script

<asp:Repeater ID="myrepeater" runat="server">
        <HeaderTemplate>
            <table style="font: 8pt verdana">
                <tr style="background-color:#3C78C3">
                    <th>Search Result</th>
                </tr>

        </HeaderTemplate>
        <ItemTemplate>
            <tr>
                <td>
                    <%#DataBinder.Eval(Container,"DataItem.allun")%>
                    <asp:Button ID="Button1" runat="server" Text="Button" />
                </td>
           </tr>
        </ItemTemplate>
        <FooterTemplate>
            </table>
        </FooterTemplate>

Code Behind

protected void btnSearch_Click(object sender, EventArgs e)
{
    con.Open();
    if (txtSearch.Text != "")
    {
        SqlDataAdapter mycommand = new SqlDataAdapter("select * from WebAdminTable where allun='" + txtSearch.Text + "'", con);
        DataSet ds = new DataSet();
        mycommand.Fill(ds);
        myrepeater.DataSource = ds;
        myrepeater.DataBind();
    }
    else
    {
        //msgbox for entering value
    }
    con.Close();
}

protected void btnAddToMyFList_Click(object sender, EventArgs e)
{
      //?    
}

回答1:

You can bind the userName to a label control and then you can access the value of the label control on the click of button like...

protected void btnAddToMyFList_Click(object sender, EventArgs e)
{
  Button btnAddToMyFList = (Button)sender;
  Label label = (Label)btnAddToMyFList.Parent.FindControl("LabelId");
  String labelText = label.Text; //userName of clicked row
}