I’ve used the following to add a table to a DataGridView on a WinForm:
void PopulateGridView() {
conn = new SqlConnection(ConfigurationManager.ConnectionStrings["IMS"].ConnectionString);
myAdapt = new SqlDataAdapter("SELECT * FROM FrontDesk.dbo.tb_xxx", conn);
mySet = new DataSet();
myAdapt.Fill(mySet, "AvailableValues");
myTable = mySet.Tables["AvailableValues"];
this.uxChargeBackDataGridView.DataSource = myTable;
this.uxChargeBackDataGridView.Columns["RefKey"].Visible = false;
}
There are 5 rows in the table, which has only 2 fields – the field RefKey is hidden from the DGV and is the primary key of the underlying table.
Why doesn’t the following work? Add seems to be the property of the Rows collection of the DGV that is used to add a row:
private void button1_Click(object sender, EventArgs e)
{
uxChargeBackDataGridView.Rows.Add(6, "dre");
}
Because the grid is using a DataTable as a source, you would have to add the row to the table. The grid should automatically reflect that:
Use the
NewRow()function on the data table to get a DataRow object that has the schema used by the data table.You wouldn’t have to create the
tablereference if you moved yourmySetandmyTablevariable to the form level scope, then you would be able to just usemyTable.Rows.Add(row);instead.