1
votes

I am not handy at this. I have a dataGridView bound to SQL by a dataset. All column are generated by the dataset except one column which is replaced by a coded one which is a comboboxColumn. To avoid new columns being generated while editing a row, I have set the allowUserToAddRows to false. Now I would like to add new empty rows by button click. I have tried in several way without any success. Updated with full code

 public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        this.affitto_saTableAdapter.Fill(this.affitto_SADataSet.affitto_sa);
        DataGridViewComboBoxColumn comboCol1 = new DataGridViewComboBoxColumn();
        comboCol1.Name = "Periodo Rif.";
        List<DateTime> periods = new List<DateTime>() { DateTime.Now.AddMonths(-2), DateTime.Now.AddMonths(-1), DateTime.Now, DateTime.Now.AddMonths(1), DateTime.Now.AddMonths(2) };
        //Dates = Dates.OrderBy(x => x).ToList();
        List<string> colSource = periods.Select(x => x.ToString("MMM/yyyy")).ToList();
        comboCol1.DataSource = colSource;
        dataGridView1.Columns.Add(comboCol1);
        comboCol1.DataPropertyName = "Periodo";
        dataGridView1.Columns["Periodo Rif."].DisplayIndex = 1;
    }

    private void button1_Click(object sender, EventArgs e)
    {
       /* DataTable dt = dataGridView1.DataSource as DataTable;
        DataRow row = dt.NewRow();
        dt.Rows.Add(row);*/

        (dataGridView1.DataSource as DataTable).Rows.Add((dataGridView1.DataSource as DataTable).NewRow());

    }
}

How can I add a new empty row to such DGV?

2
This code should work. Can you please explain what went wrong? PS: bear in mind that a blank row for a combobox column means a combobox (with -1 as selectedindex, that is, no item selected).varocarbas
@varocarbas, with the above code I get a null reference exception and I do not understand why.FeliceM
I have tried your code (by adding a proper datasource to the DataGridView, what is not present in what you posted) and everything is fine. Can you please include the part where you set the DataSource?varocarbas
@varocarbasI updated the question with the full code I have in this app.FeliceM
as DataTable expects a DataTable as DataSource, if this is not the case you are casting to the wrong type. Perhaps you prefer to set the DataSource at runtime (with a DataTable). Don't populate anything from the design view, create a DataTable (dt) variable and populate it from the source you want (a DB, I understand), write DataGridView1.DataSource = dt and your code would work.varocarbas

2 Answers

1
votes

Here solution for your problem:

dataGridView1.Rows.AddCopy(myDataGridView1.Rows.Count - 1);

Since your DGV not binded with any of dataSource hence AddCopy of DataGridViewRow will add new row at end of DGV (at Rows.Count - 1).

0
votes
 private void button1_Click(object sender, EventArgs e)

    {

        this.dataGridView1.Rows.Add();

    }