I\'m struggling to create this script where it generates friend requests. I need to specifically add an id to each button and label so I can remove it when the user clicks eithe
The first thing to do is to retrieve from your query the value that uniquely identifies your data. Suppose that your PendingRequest table has an IDRequest then your query could be changed to
using (SqlCommand cmd = new SqlCommand(@"Select IDRequest, UserFirstName,
UserLastName, FriendEmail
From PendingRequests
Where FriendEmail = @fe", connection))
Now when you create your controls dynamically you add also that ID to the Tag property of every control created by that record
foreach (object request in i.ToString())
{
Label userName = new Label();
Button accept = new Button();
Button reject = new Button();
int idRequest = Convert.ToInt32(dr["IDRequest"]);
userName.Tag = idRequest;
accept.Tag = idRequest;
reject.Tag = idRequest;
....
Finally in your click event you could retrieve the exact instance of the buttons and label using a code like this
private void Reject_Click(object sender, EventArgs e)
{
Button c = sender as Button;
int idRequest = Convert.ToInt32(c.Tag);
var ctrls = friendRequestPanel.Controls
.Cast()
.Where(x => x.Tag != null &&
Convert.ToInt32(x.Tag) == idRequest)
.ToList();
foreach(Control ct in ctrls)
{
friendRequestPanel.Controls.Remove(ct);
ct.Dispose();
}
updateFriendRequestDatabase(2);
}
Notice that if you remove the control from the Controls collection you should not forget to Dispose it.