在DataGridView中设置最大行数?

时间:2017-09-11 12:09:58

标签: c# visual-studio oop visual-studio-2013 datagridview

我有一个程序,一旦用户单击按钮就会向DataGridView添加行。我需要将行数限制为最多10个。

这是我的代码:

public partial class Form1 : Form 
{
    private Int32 MaxRows { get; set; }

    public Form1()
    {
        MaxRows = 10;
        InitializeComponent();

        dataGridView1.UserAddedRow += dataGridView1_RowCountChanged;
        dataGridView1.UserDeletedRow += dataGridView1_RowCountChanged;
    }

    private void dataGridView1_RowCountChanged(object sender, EventArgs e)
    {
        CheckRowCount();
    }

    private void CheckRowCount()
    {
        if (dataGridView1.Rows != null && dataGridView1.Rows.Count > MaxRows)
        {
            dataGridView1.AllowUserToAddRows = false;
        }
        else if (!dataGridView1.AllowUserToAddRows)
        {
            dataGridView1.AllowUserToAddRows = true;
        }
    }

    public void button1_Click(object sender, EventArgs e)
    {
        this.dataGridView1.Rows.Add("This is a row.");
    }

}

我从这里发布的另一个问题得到了代码(似乎找不到链接),但代码不起作用,我可以在我的DataGridView中创建超过11行。为什么会发生这种情况的任何原因?

2 个答案:

答案 0 :(得分:0)

也许这种方式更容易?

private Int32 MaxRows { get; set; }

public Form1()
{
    MaxRows = 10;
    InitializeComponent();
}

public void button1_Click(object sender, EventArgs e)
{
    if (dataGridView1.Rows.Count <= MaxRows)
    this.dataGridView1.Rows.Add("This is a row.");
}

此外,AllowUserToAddRows属性为:&#34;如果向用户显示add-row选项,则为true;否则为true。否则是假的。默认为true&#34;与从添加行的位置后面的代码添加行无关。它指的是在应用程序运行时通过单击数据网格将新行添加到网格中的选项。

答案 1 :(得分:0)

CheckRowCount()可以简化。您只需在达到最大限制时禁用AllowUserToAddRows

private void CheckRowCount()
    {
        // The data grid view's default behavior is such that it creates an additional row up front.
        // e.g. when you add 1st row, it creates 2nd row automatically.
        // If you use Count < MaxRows, the user won't be able to add the 10th row.
        if (dataGridView1.Rows.Count <= MaxRows)
        {
            dataGridView1.AllowUserToAddRows = true;
        }
        else
        {
            dataGridView1.AllowUserToAddRows = false;
        }
    }

在按钮单击时添加新行时,请确保当前行数小于MaxRows。您还应调用CheckRowCount方法以确保相应地设置AllowUserToAddRows。修改按钮单击处理程序,如下所示:

private void button1_Click(object sender, EventArgs e)
    {
        // If the rows count is less than max rows, add a new one.
        if (dataGridView1.Rows.Count < MaxRows)
        {
            this.dataGridView1.Rows.Add("This is a row.");

            // Check the row count again.
            CheckRowCount();
        }
    }