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?
as DataTable
expects aDataTable
asDataSource
, if this is not the case you are casting to the wrong type. Perhaps you prefer to set theDataSource
at runtime (with aDataTable
). Don't populate anything from the design view, create aDataTable
(dt
) variable and populate it from the source you want (a DB, I understand), writeDataGridView1.DataSource = dt
and your code would work. – varocarbas