如何创建C#按钮数组?

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

我想要做的是:我有一些日历安排的按钮,表示时间段。 IE:周一0700Button,周一0730Button,周一0800Button,依此类推30分钟。

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

有任何想法吗? 谢谢。

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

 List 

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

很久以前,我使用二维数组按钮为计算器应用程序构建UI。 我很长一段时间都使用过HP-15C,但错过了它。

替代文字

arrays方法运行良好。

  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) ) ; } } } 

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

如果我理解正确,您应该能够向表单添加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); } 

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

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

像所有GUI元素一样,按钮就像任何其他对象一样(也可能是可显示的)。 所以是的,你可以拥有数组,列表,字典 – 无论你想要什么包含按钮。 Taylor的回复有一些示例代码。

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