jeśli dodać wiersz do DataTable
.
DataRow row = datatable1.NewRow();
row["column2"]="column2";
row["column6"]="column6";
datatable1.Rows.Add(row);
A co z DataGridView
?
Możesz to zrobić:
DataGridViewRow row = (DataGridViewRow)yourDataGridView.Rows[0].Clone();
row.Cells[0].Value = "XYZ";
row.Cells[1].Value = 50.2;
yourDataGridView.Rows.Add(row);
lub:
DataGridViewRow row = (DataGridViewRow)yourDataGridView.Rows[0].Clone();
row.Cells["Column2"].Value = "XYZ";
row.Cells["Column6"].Value = 50.2;
yourDataGridView.Rows.Add(row);
Inny sposób:
this.dataGridView1.Rows.Add("five", "six", "seven","eight");
this.dataGridView1.Rows.Insert(0, "one", "two", "three", "four");
Od: http://msdn.microsoft.com/en-us/library/system.windows.forms.datagridview.rows.aspx
Na przykład to:
dataGridView1.Columns[0].Name = "column2";
dataGridView1.Columns[1].Name = "column6";
string[] row1 = new string[] { "column2 value", "column6 value" };
dataGridView1.Rows.Add(row1);
Lub trzeba ustawić tam wartości indywidualnie użyć propery .Rows()
, jak to:
dataGridView1.Rows[1].Cells[0].Value = "cell value";
Dodanie nowego wiersza w DGV bez wierszy za pomocą Add() powoduje wywołanie zdarzenia SelectionChanged zanim będzie można wstawić jakiekolwiek dane (lub powiązać obiekt we właściwości Tag).
Tworzenie sklonowanego wiersza z RowTemplate jest bezpieczniejsze imho:
//assuming that you created columns (via code or designer) in myDGV
DataGridViewRow row = (DataGridViewRow) myDGV.RowTemplate.Clone();
row.CreateCells(myDGV, "cell1", "cell2", "cell3");
myDGV.Rows.Add(row);