如何从窗体中清除按钮控件

时间:2013-03-02 19:56:42

标签: c# winforms

我的表格是空白的,除了新游戏和退出顶部的菜单条。加载表单时,它会填充一个按钮网格,其尺寸从App.config文件中读取。清除表格中为新游戏放置的所有按钮的最佳方法是什么?

this.Controls.Clear();

上述方法不起作用,因为它也删除了表单顶部的菜单条,它只允许我从表单中调用它。我还有一个函数,我在Gameboard类中运行程序

    public void ClearButtons()
    {

        for (int q = 0; q < buttonArray.Length; q++)
        {
            buttonArray[q].Text = "";
            buttonArray[q].Enabled = true;
            buttonArray[q].BackColor = Color.LightGray;
        }
    }

但必须有一个更好的方法来做到这一点,如果我可以重新加载表单,它会用所需的按钮重新填充它但我似乎无法弄清楚,特别是从我的游戏板类。谢谢大家。

4 个答案:

答案 0 :(得分:2)

1)您可以使用以下代码删除所有按钮,而不是清除:

  public void ClearButtons()
  {
    for (int i = 0; i < this.Controls.Count; i++)
    {
       if (Controls[i] is Button)
       {
         Controls.RemoveAt(i);
         i--;
       }
    }
  }

2)如果要从另一个类调用此代码,则必须将表单实例传递给它,例如作为构造函数参数

3)创建public void MyInits()函数并将代码从Form1_Load移到那里。然后从Form1_Load

中调用它

4)编辑构造函数

public Gameboard(int numberofButtons, Form1 frm)

并传递this然后实例化它。而不是在构造函数中调用frm.MyInits();

答案 1 :(得分:0)

而不是使用this.Controls.Clear

你可以循环执行此操作。控制,并测试它是否是一个Button然后将其删除。

更好的方法是创建容器,面板或其他类似的东西,然后在其中创建按钮并使用

this.Controls.Remove(myPanel);
myPanel.Dispose();

答案 2 :(得分:0)

所以这是我的Gameboard构造函数,Ill会告诉你Form如何调用它来填充底部的按钮。

public Gameboard(int numberofButtons) //Constructor method that is referencing the App.config for the dimensions value to make the board
    {
        if (numberofButtons <= 0) 
            throw new ArgumentOutOfRangeException("Invalid Grid"); //throws an exception for an invalid grid size if dimensions is equal to or less than zero

        buttonArray = new Button[numberofButtons]; //creating an array the size of numberofButtons which is the dimensions value from App.config
        Font font = new Font("Times New Roman", 36.0f); //creates an instance of the Font class
        int sqrtY = (int) Math.Sqrt(numberofButtons);
        int z = 0; //Counter for array

        //Create the buttons for the form
        //Adds the buttons to the form first with null values then changes the .Text to ""
        for (int x = 0; x < sqrtY; x++)
        {
            for (int y = 0; y < sqrtY; y++)
            {
                buttonArray[z] = new Button();
                buttonArray[z].Font = font;
                buttonArray[z].Size = new System.Drawing.Size(100, 100);
                buttonArray[z].Location = new System.Drawing.Point(100*y, 100*x);
                buttonArray[z].Click += new EventHandler(button_click);
                z++; 
            }
        }//At the end of this loop, buttonArray contains a number of buttons equal to Dimensions all of which have a .Text property of ""
    }

所以这是表单加载的时候:

    private void Form1_Load(object sender, EventArgs e)
    {
        try
        {
            //Read the App.Config file to get the dimensions of the grid
            int dimensions = Convert.ToInt16(ConfigurationManager.AppSettings["dimensions"]);

            //Create the gameboard object with all the buttons needed
            Gameboard gb = new Gameboard(dimensions); //Calls the Gameboad constructor method

            //Add buttons to the form
            for (int x = 0; x < gb.buttonArray.Length; x++)
            {
                this.Controls.Add(gb.buttonArray[x]);
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.ToString());
        }
    }

清除表单上的按钮后,我需要调用什么来重新运行Form_Load以便重新填充?

答案 3 :(得分:-1)

' Calculates the date of the occurrence of Weekday in the month of DateInMonth.
'
' If Occurrence is 0 or negative, the first occurrence of Weekday in the month is assumed.
' If Occurrence is 5 or larger, the last occurrence of Weekday in the month is assumed.
'
' If Weekday is invalid or not specified, the weekday of DateInMonth is used.
'
' 2016-06-09. Gustav Brock, Cactus Data ApS, CPH.
'
Public Function DateWeekdayInMonth( _
    ByVal DateInMonth As Date, _
    Optional ByVal Occurrence As Integer, _
    Optional ByVal Weekday As VbDayOfWeek = -1) _
    As Date

    Const DaysInWeek    As Integer = 7

    Dim Offset          As Integer
    Dim Month           As Integer
    Dim Year            As Integer
    Dim ResultDate      As Date

    ' Validate Weekday.
    Select Case Weekday
        Case _
            vbMonday, _
            vbTuesday, _
            vbWednesday, _
            vbThursday, _
            vbFriday, _
            vbSaturday, _
            vbSunday
        Case Else
            ' Zero, none or invalid value for VbDayOfWeek.
            Weekday = VBA.Weekday(DateInMonth)
    End Select

    ' Validate Occurence.
    If Occurrence <= 0 Then
        Occurrence = 1
    ElseIf Occurrence > 5 Then
        Occurrence = 5
    End If

    ' Start date.
    Month = VBA.Month(DateInMonth)
    Year = VBA.Year(DateInMonth)
    ResultDate = DateSerial(Year, Month, 1)

    ' Find offset of Weekday from first day of month.
    Offset = DaysInWeek * (Occurrence - 1) + (Weekday - VBA.Weekday(ResultDate) + DaysInWeek) Mod DaysInWeek
    ' Calculate result date.
    ResultDate = DateAdd("d", Offset, ResultDate)

    If Occurrence = 5 Then
        ' The latest occurrency of Weekday is requested.
        ' Check if there really is a fifth occurrence of Weekday in this month.
        If VBA.Month(ResultDate) <> Month Then
            ' There are only four occurrencies of Weekday in this month.
            ' Return the fourth as the latest.
            ResultDate = DateAdd("d", -DaysInWeek, ResultDate)
        End If
    End If

    DateWeekdayInMonth = ResultDate

End Function