【问题标题】:How to add click event and write text to a flowpanel如何添加点击事件并将文本写入流程面板
【发布时间】:2015-12-28 10:13:41
【问题描述】:

我有这个创建按钮的方法:

        Button[] CreatingButtons(int n, List<string> names)
    {
        Button[] Buttons = new Button[n];
        int horizontal = 180; int vertical = 5;
        int Height = 33; int Width = 350 / Buttons.Length;
        for (int i = 0; i < Buttons.Length; i++)
        {
            Buttons[i] = new Button();
            Buttons[i].Height = Height;
            Buttons[i].Width = Width;
            this.Controls.Add(Buttons[i]);
            Buttons[i].Text = names[i];
            Buttons[i].TextAlign = ContentAlignment.MiddleCenter;
            Buttons[i].Location = new Point(horizontal, vertical);
            horizontal += Buttons[i].Width;
            Buttons[i].Click += (o, k) => 
            {

            };
        }
        return Buttons;
    }

如您所见,点击事件仍然是空的。我也有FlowDirectionPanel,称为textPanel

我需要点击事件在这个面板中显示一些文本,还有一些图像,每个按钮都会显示不同的东西。我怎样才能做到这一点 ?我以前从未使用过面板

【问题讨论】:

  • 你想在哪里显示一些文本以及你想根据每次按钮点击如何显示?
  • 我想在名为 textPanel 的 flowdirectionpanel 中显示文本,每个按钮都会显示不同的内容
  • 你的按钮数组中是否有任何东西可以区分每个按钮
  • 好吧,我在这里用这个函数创建了 4 个不同的按钮数组,所以是的,有

标签: c# arrays events button click


【解决方案1】:

不清楚您真正想在面板中显示什么,但您可以将 TextBoxPictureBox 放置到面板并更改它们的 TextImage 属性。

List<string> textValues=new List<string> {"A","B",...}; //Add your different values to the list
List<Image> imgValues=new List<string> {image1,image2,...}; //Add your different images to the list

Buttons[i].Click += (o, k) => 
            {
              textBox1.Text= textValues[i];
              pictureBox1.Image= imgValues[i];
            };

【讨论】:

  • 我认为我应该将这些添加为面板的子项
  • op 想要在每个按钮上显示不同的东西你不认为每个按钮都应该使用你的代码生成相同的东西,除了 i
【解决方案2】:

根据 cmets,您正在创建四个不同的按钮数组,因此最好使用类和属性而不是像

这样的按钮数组

你必须声明一个像

这样的类
 internal class ButtonsDetails
    {
        public string Text { get; set; }
        public Image imgsource { get; set; }
    }

你的按钮生成方法应该是

private static void GenerateButton(List<ButtonsDetails> details)
        {
            foreach (var item in details)
            {
                Button b = new Button();
                b.Click += (o, k) =>
                {
                    textBox1.Text = item.Text
                    pictureBox1.Image = item.imgsource
                };
            }
        }

【讨论】:

  • 好吧,第一个数组有 3 个按钮,它们都会显示不同的东西
  • 那么按钮数组应该不起作用,您必须声明一个类,因为您必须声明属性并创建该类的集合并使用它
  • @QuestionsEverywhere:让我知道你到底想用它做什么,这样我就可以为你创建示例
  • 我使用我的问题中的方法创建了 4 个不同的数组,每个数组有 3 个按钮,每个按钮都有不同的文本和图像显示在 flowdirectionpanel 中
  • @QuestionsEverywhere:您的意思是 List names 中的按钮名称?
猜你喜欢
  • 2012-09-26
  • 1970-01-01
  • 1970-01-01
  • 2023-04-03
  • 2014-04-23
  • 2017-09-29
  • 1970-01-01
  • 2013-06-07
  • 1970-01-01
相关资源
最近更新 更多