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
@Steve has answered it all well. He has already shown you how to fix your current code.
I want to suggest you a better way to structure your current code, so that it looks cleaner and you have more control over the friend request functionality. If you are interested, read further. If you are on tight deadlines then ignore :).
If I was in your place, I would create a user control to represent individual friend request and use events to notify main form in case of accept/reject so that it can remove the request from panel/list. This way main form code (designer + code behind) will become cleaner to read and understand.
FriendRequestControl
This would be standard UserControl
which has contains 1 Label
(for displaying friend's name and 2 Buttons
accept and reject.
public partial class FriendRequestControl : UserControl
{
public event EventHandler Accepted;
public event EventHandler Rejected;
public FriendRequestControl()
{
InitializeComponent();
}
public int RequestId { get; set; }
public string FriendName { set { lblFriend.Text = value; } } // TODO add empty/null checks on value
private void Accept_Click(object sender, EventArgs e)
{
UpdateRequest(1);
OnAccepted();
}
private void Reject_Click(object sender, EventArgs e)
{
UpdateRequest(2);
OnRejected();
}
private bool UpdateRequest(int flag)
{
// Update db using RequestId and flag
// TODO Return True/False based if update succeeds
return true;
}
private void OnAccepted()
{
var acceptedHandler = Accepted;
if (acceptedHandler != null)
{
acceptedHandler(this, EventArgs.Empty);
}
}
private void OnRejected()
{
var rejectedHandler = Rejected;
if (rejectedHandler != null)
{
rejectedHandler(this, EventArgs.Empty);
}
}
}
Main Form
private void Form1_Load(object sender, EventArgs e)
{
// Showing just 1 request here
var friendRequest = new FriendRequestControl
{
RequestId = 100, // As Steve mentioned, you db must return this.
FriendName = "Friend 1"
};
friendRequest.Accepted += FriendRequest_Accepted;
friendRequest.Rejected += FriendRequest_Rejected;
flowLayoutPanel1.Controls.Add(friendRequest);
}
private void FriendRequest_Rejected(object sender, EventArgs e)
{
var friendRequest = sender as FriendRequestControl;
flowLayoutPanel1.Controls.Remove(friendRequest);
}
private void FriendRequest_Accepted(object sender, EventArgs e)
{
var friendRequest = sender as FriendRequestControl;
flowLayoutPanel1.Controls.Remove(friendRequest);
}