I have these two methods that correctly populate a datagridview. The question is what do I need to add to get any changes committed to the SQL tables in the database? I can change values in the grid but those changes are not being committed to the database.
private void InitializeDataGridView()
{
try
{
// Set up the data source.
bindingSourceStations.DataSource = GetData("SELECT [STATIONID] AS 'Station ID',[STATNAME] AS 'Station Name' FROM [WXDATA].[dbo].[STATIONS]");
dgvStations.DataSource = bindingSourceStations;
// Automatically resize the visible rows.
dgvStations.AutoSizeRowsMode =
DataGridViewAutoSizeRowsMode.DisplayedCellsExceptHeaders;
// Set the DataGridView control's border.
dgvStations.BorderStyle = BorderStyle.Fixed3D;
// Put the cells in edit mode when user enters them.
dgvStations.EditMode = DataGridViewEditMode.EditOnEnter;
}
catch (SqlException)
{
MessageBox.Show("To run this sample replace connection.ConnectionString" +
" with a valid connection string to the stations" +
" database accessible to your system.", "ERROR",
MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
System.Threading.Thread.CurrentThread.Abort();
}
}
private static DataTable GetData(string sqlCommand)
{
string connectionString = DataAccess.ConnectionStringSQL(Controller.Instance.Model.SQLDatabase);
SqlConnection stationsConnection = new SqlConnection(connectionString);
SqlCommand command = new SqlCommand(sqlCommand, stationsConnection);
SqlDataAdapter adapter = new SqlDataAdapter();
adapter.SelectCommand = command;
DataTable table = new DataTable();
table.Locale = System.Globalization.CultureInfo.InvariantCulture;
adapter.Fill(table);
return table;
}
ASKER
private void btnSave_Click(object sender, EventArgs e)
{
dgvStations.EndEdit(); //very important step
adapter.Update(dataTable); // use the adapter to update the data in the data table.
MessageBox.Show("Updated");
PopulateDataGridView(); // Should probably be renamed to something else as initialize implies only on creation.
}