1
votes

I have a problem with datagridview in my windows form application. I set AllowUserToAddRows=true, so on user double click on last blank rows, the selected cell goes in edit mode and when user write something in the textboxcolumn a new row is added.

This is all fine, but now I would that when new row is edit by user(double click) all the fields are filled with default values, for example using values from first row, so I set DefaultValuesNeeded event on my datagridview and in code behind I fill all field in the selected row.

The problem is that now no new row appear on bottom after DefaultValuesNeeded fire.

How can I solve this issue ?

1
Do you have a binding source to your DataGridView?Moop

1 Answers

0
votes

If you have a binding source to your DataGridView, you can call EndCurrentEdit() in the DefaultValuesNeeeded event handler to commit the new row immediately with the default values.

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

If you don't have a binding source, we cannot using the DefaultValuesNeeded event since it doesn't work. But we can simulated it by capturing the CellEnter event.

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