I want to add new row to existing datagridview. There is a problem beacause datagridview is connected to datasource and I can't add row by Rows.Add(). I have tried all commented lines and nothing works. Here is my code:
private void SaveButton_Click(object sender, EventArgs e)
{
if (start_tab == start_picker.ToString("dd-MM-yyyy HH:mm:00") & stop_tab != stop_picker.ToString("dd-MM-yyyy HH:mm:00"))
{
DateTime new_starttime = stop_picker;
DateTime new_stoptime = Convert.ToDateTime(stop_tab);
int new_cycletime = Convert.ToInt32(dataGridView3.Rows[dataGridView3.CurrentRow.Index].Cells["cycle_time"].Value) - Convert.ToInt32(textBox32.Text);
//devents.Rows.Add(new_starttime, new_stoptime, new_cycletime);
//DataTable devents = new DataTable();
//DataTable devents =
//DataRow newRow = devents.NewRow();
//newRow["start_time"] = new_starttime;
//newRow["stop_time"] = new_stoptime;
//newRow["cycle_time"] = new_cycletime;
//devents.Rows.Add(newRow);
dataGridView3.Rows.RemoveAt(dataGridView3.CurrentCell.RowIndex);
dataGridView3.Update();
dataGridView3.Refresh();
}
}
Data to datagridView is loaded from another private void:
private void Openbutton_Click(object sender, EventArgs e)
{
OpenReport();
EventClass eventData = new EventClass();
DataTable devents = eventData.Load_downtimes();
dataGridView3.DataSource = devents;
CodePudding user response:
Adding to the DataTable should actually work.
The question is how you got devents
here, it is declared locally in Openbutton_Click below.
You can best get it directly from the dgv (must be cast because DataSource can have various types)
var devents = (DataTable)dataGridView3.DataSource;
DataRow newRow = devents.NewRow();
newRow["start_time"] = new_starttime;
newRow["stop_time"] = new_stoptime;
newRow["cycle_time"] = new_cycletime;
devents.Rows.Add(newRow);