C# Can';使用DataGridView中所需的默认值时,不能添加新行

C# Can';使用DataGridView中所需的默认值时,不能添加新行,c#,.net,winforms,datagridview,C#,.net,Winforms,Datagridview,我的windows窗体应用程序中的datagridview有问题。 我将AllowUserToAddress设置为true,这样当用户双击最后一个空白行时,所选单元格将进入编辑模式,当用户在textboxcolumn中写入内容时,将添加新行 这很好,但现在我希望当用户编辑新行(双击)时,所有字段都用默认值填充,例如使用第一行中的值,因此我在datagridview上设置DefaultValuesNeed事件,并在代码隐藏中填充所选行中的所有字段 问题是,在DefaultValuesNeedFir

我的windows窗体应用程序中的datagridview有问题。 我将AllowUserToAddress设置为true,这样当用户双击最后一个空白行时,所选单元格将进入编辑模式,当用户在textboxcolumn中写入内容时,将添加新行

这很好,但现在我希望当用户编辑新行(双击)时,所有字段都用默认值填充,例如使用第一行中的值,因此我在datagridview上设置DefaultValuesNeed事件,并在代码隐藏中填充所选行中的所有字段

问题是,在DefaultValuesNeedFire之后,现在底部没有新的行出现


如何解决此问题?

如果您有到DataGridView的绑定源,可以调用
DefaultValuesNeeded
事件处理程序中的
EndCurrentEdit()
,以立即使用默认值提交新行

    {
        dt = new DataTable();
        dt.Columns.Add("Cat");
        dt.Columns.Add("Dog");

        dataGridView1.AllowUserToAddRows = true;
        dataGridView1.DefaultValuesNeeded += dataGridView1_DefaultValuesNeeded;

        dataGridView1.DataSource = dt;          
    }

    void dataGridView1_DefaultValuesNeeded(object sender, DataGridViewRowEventArgs e)
    {
        var dgv = sender as DataGridView;
        if(dgv == null)
           return;

        e.Row.Cells["Cat"].Value = "Meow";
        e.Row.Cells["Dog"].Value = "Woof";

        // This line will commit the new line to the binding source
        dgv.BindingContext[dgv.DataSource].EndCurrentEdit();
    }
如果没有绑定源,则无法使用
defaultvaluesneed
事件,因为它不起作用。但是我们可以通过捕获
cellcenter
事件来模拟它

    {
        dataGridView1.Columns.Add("Cat", "Cat");
        dataGridView1.Columns.Add("Dog", "Dog");

        dataGridView1.AllowUserToAddRows = true;
        dataGridView1.CellEnter += dataGridView1_CellEnter;    
    }

    void dataGridView1_CellEnter(object sender, DataGridViewCellEventArgs e)
    {
        var dgv = sender as DataGridView;
        if (dgv == null)
            return;

        var row = dgv.Rows[e.RowIndex];

        if (row.IsNewRow)
        {
            // Set your default values here
            row.Cells["Cat"].Value = "Meow";
            row.Cells["Dog"].Value = "Woof";

            // Force the DGV to add the new row by marking it dirty
            dgv.NotifyCurrentCellDirty(true);
        }
    }

您有到DataGridView的绑定源吗?谢谢,但我还没有绑定源,用户通过编辑字段并添加新数据将数据添加到我的gridview中rows@tulkas85我添加了一节,介绍如何在没有绑定源代码的情况下执行此操作