如何创建一个 C# 按钮数组?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1678249/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 19:55:31  来源:igfitidea点击:

How do I create a C# Array of Buttons?

c#arrayswinformsgenericsbutton

提问by The Woo

How do I build an array of buttons in a Winforms application?

如何在 Winforms 应用程序中构建一组按钮?

What I am trying to do is this: I have a lot of buttons in a sort of calendar arrangement, that are indicating time slots. IE: Monday0700Button, Monday0730Button, Monday0800Button, and so on in 30min intervals.

我想要做的是:我有很多按日历排列的按钮,它们指示时间段。IE:Monday0700Button、Monday0730Button、Monday0800Button 等等,以 30 分钟为间隔。

I have a xml database, where one of the fields for appointments is <Duration>When the duration = 0.5hrs, and the <Time>field equals "07:00am", to color the 'Monday0700Button'. When the Duration is 1.0hrs, I want it to populate 'Monday0700Button' as well as the following time slot button of 'Monday0730Button'.

我有一个 xml 数据库,其中约会字段之一是<Duration>持续时间 = 0.5 小时,<Time>字段等于“07:00am”,为“Monday0700Button”着色。当 Duration 为 1.0hrs 时,我希望它填充“Monday0700Button”以及“Monday0730Button”的以下时间段按钮。

Any ideas? Thanks.

有任何想法吗?谢谢。

采纳答案by Taylor Leese

Yes, you can build a list of buttons like below.

是的,您可以构建如下所示的按钮列表。

List<Button> listOfButtons = new List<Button>();
listOfButtons.Add(yourButton);

回答by Cheeso

Yes, it's no problem to build an array of Buttons, or any object. You won't be able to see them in the Visual studio designer, but they'll work just fine.

是的,构建一个 Button 数组或任何对象都没有问题。您将无法在 Visual Studio 设计器中看到它们,但它们会正常工作。

A long time ago I used a 2-D array of buttons to build the UI for an calculator app. I had used an HP-15C for a long time, and missed it.

很久以前,我使用二维按钮阵列来构建计算器应用程序的 UI。我使用 HP-15C 很长时间了,但错过了。

alt text

替代文字

The array approach worked fine.

阵列方法工作正常。

  Button[] numberButtons=new Button[] { btn0, btn1, btn2, btn3, btn4, btn5, btn6, btn7, btn8, btn9, btnDecimalPt};
  Button[] operationButtons=new Button[] { btnDiv, btnMult, btnSubtract, btnAdd };

  foreach (var b in numberButtons)
       b.Click += new System.EventHandler(this.Number_Click);

  foreach (var b in operationButtons)
      b.Click += new System.EventHandler(this.Operation_Click);

  // etc

  Button[][] allButtons=
  {
      new Button[] {btnSqrt, btnExp, btn10x, btnPow,btnMultInverse, btnCHS, null, null, null, null}, 
      new Button[] {btnN, btnInterest, btnPMT, btnPV, btnFV, null, btn7, btn8, btn9, btnDiv}, 
      new Button[] {btnLn, btnLog, btnSine, btnCosine, btnTangent, btnPi, btn4, btn5, btn6, btnMult}, 
      new Button[] {btnRoll, btnSwap, btnCLRfin, btnCLX, btnCLR, btnEnter, btn1, btn2, btn3, btnSubtract}, 
      new Button[] {btnInt, btnFrac, btnFix, btnStore, btnRecall, null, btn0, btnDecimalPt, btnNotUsed, btnAdd}
  };

  // programmatically set the location
  int col,row;
  for(row=0; row < allButtons.Length; row++)
  {
      Button[] ButtonCol= allButtons[row];
      for (col=0; col < ButtonCol.Length; col++)
      {
          if (ButtonCol[col]!=null)
          {
              ButtonCol[col].TabIndex = col + (row * allButtons.Length) +1;
              ButtonCol[col].Font = font1; 
              ButtonCol[col].BackColor = System.Drawing.SystemColors.ControlDark;
              ButtonCol[col].Size=new System.Drawing.Size(stdButtonWidth, stdButtonHeight);
              ButtonCol[col].Location=new Point(startX + (col * stdButtonWidth), 
                                                startY + (row * stdButtonHeight) ) ;
          }
      }
  }

回答by Smashery

Buttons, like all GUI elements, are objects just like any other (that also happen to be displayable). So yes, you can have arrays, lists, dictionaries - whatever you want containing buttons. Taylor L's responsehas some sample code.

按钮与所有 GUI 元素一样,是与其他任何对象一样的对象(也恰好是可显示的)。所以是的,你可以拥有数组、列表、字典——任何你想要的包含按钮的东西。Taylor L 的回复有一些示例代码。

回答by FrustratedWithFormsDesigner

Yes, this is possible, as Taylor L demonstrated. The only catch is that VB6-style control arrays, created by copying and pasting the control, can no longer be done in the forms editor.

是的,这是可能的,正如 Taylor L 所证明的那样。唯一的问题是通过复制和粘贴控件创建的 VB6 样式的控件数组不能再在表单编辑器中完成。

回答by senfo

Yep, definitely possible, but probably unnecessary.

是的,绝对有可能,但可能没有必要。

If I understand you correctly, you should be able to add a FlowLayoutPanelto your Form and then loop through your XML, instantiating a new Button, as necessary. Wire up the event handler for the Click event, then add the button to the FlowLayoutPanel by calling the Add() method off of the Controls property on your FlowLayoutPanel.

如果我理解正确,您应该能够将FlowLayoutPanel添加到您的表单,然后循环浏览您的 XML,根据需要实例化一个新的 Button。为 Click 事件连接事件处理程序,然后通过调用 FlowLayoutPanel 上 Controls 属性的 Add() 方法将按钮添加到 FlowLayoutPanel。

while (reader.Reader())
{
    // Parse XML here

    // Instantiate a new button that will be added to your FlowLayoutPanel
    Button btn = new Button();

    // Set button properties, as necessary
    btn.Text = "Foo";
    btn.Click += new EventHandler(SomeButton_Click);

    // Add the button to the FlowLayoutPanel
    flowLayoutPanel.Controls.Add(btn);
}

While a FlowLayoutPanel makes it easy to do the layout for your buttons, it might not work for you. If that's the case, you will have to work out the X and Y coordinates for your buttons as you loop through the XML.

虽然 FlowLayoutPanel 可以轻松地为您的按钮进行布局,但它可能不适合您。如果是这种情况,则必须在循环浏览 XML 时计算按钮的 X 和 Y 坐标。

One problem that you will encounter with the above approach is that it always calls the exact same event handler. As a result, you will have to come up with a way to determine which button has been clicked. One approach might be to extend the Button control to provide additional properties that can be used to acknowledge the time period.

使用上述方法会遇到的一个问题是它总是调用完全相同的事件处理程序。因此,您将不得不想出一种方法来确定已单击了哪个按钮。一种方法可能是扩展 Button 控件以提供可用于确认时间段的其他属性。