winforms 在同一列表中的项之间进行交互C#(win forms)

gzszwxb4  于 2022-11-17  发布在  C#
关注(0)|答案(2)|浏览(137)

我试图创建一个按钮列表和一个文本框列表,我需要在这些元素之间进行交互。我的意思是,每当我单击按钮时,我需要对同一行中的文本框执行一些操作。我试图在单击事件上使用委托,但我真的找不到一种方法来指向我要指向的文本框。

private void button1_Click(object sender, EventArgs e)
    {
        OpenFileDialog openFileDialog = new OpenFileDialog();
        openFileDialog.Multiselect = true;
        openFileDialog.ShowDialog();

        string[] files = openFileDialog.FileNames.ToArray();

        int index = 0;

        List<Button> EditButtons = new List<Button>();
        List<TextBox> TextBoxes = new List<TextBox>();

        foreach (var file in files)
        {
            EditButtons.Add(new Button() { Text = "Edit", Top = index +50, Left = 150 });
            TextBoxes.Add(new TextBox() { Text = file, Top = index +50, Left = 5 });
            index = index + 25;
        }

        foreach (Button button in EditButtons)
        {
            Controls.Add(button);
        }

        foreach (TextBox textBox in TextBoxes)
        {
            Controls.Add(textBox);
        }
    }
3vpjnl9f

3vpjnl9f1#

标记方法的工作原理与上一个答案中描述的相同,此代码片段应该可以工作,只需根据需要更改pnlTextBox和pnlButtons即可:

private void button1_Click(object sender, EventArgs e)
    {
        OpenFileDialog openFileDialog = new OpenFileDialog();
        openFileDialog.Multiselect = true;
        openFileDialog.ShowDialog();
        string[] files = openFileDialog.FileNames.ToArray();

        int index = 0;

        
        foreach (var file in files)
        {
            var button = new Button()  { Text = "Edit", Top = index +50, Left = 150 };
            var textBox = new TextBox() { Text = file, Top = index +50, Left = 5 };

                button.Tag = textBox;
                button.Click += Button_Click;

            pnlTextBox.Controls.Add(textBox);//Add the textbox to the container i used a panel here
            pnlButtons.Controls.Add(button);//Add the button to the container i used a panel here

            index = index + 25;
        }
       
    }

private void Button_Click(object sender, EventArgs e)
   {
    var button=((Button)sender);
    var textBox = ((TextBox)(button.Tag));
    textBox.Text = button.Text;//example to access the proper textbox
   }
wb1gzix0

wb1gzix02#

有许多方法可以处理这个问题。您可以在创建文本框时将其粘贴到按钮的Tag属性中,如下所示:

foreach (var file in files)
{
    var txt = new TextBox() { Text = file, Top = index +50, Left = 5 };
    var btn = new Button() { Text = "Edit", Top = index +50, Left = 150, Tag = 
        txt };
    EditButtons.Add(btn);
    TextBoxes.Add(txt);
    index = index + 25;
}

然后在处理click事件时使用以下行获取文本框:

var txt = (sender as Button).Tag

显然还有其他的方法,比如把按钮和文本框放进字典里,但我认为这是最简单的方法。

相关问题