c# How to create buttons and delete them later by an ID

前端 未结 2 1403
广开言路
广开言路 2021-01-22 14:39

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

2条回答
  •  深忆病人
    2021-01-22 15:12

    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.

提交回复
热议问题