I have a C# winform that correctly display a list of users. I would like to give the users the ability to change values within the datagridview and then provide a Save button to commit the changes to the database. I found solutions using a data table but I am not using a data table. Can this be done using the code below? If so, what would the code under the Save button look like.
private void DisplayUserList()
{
try
{
/* Instantiate the data set */
_ds = new DataSet();
_ds.CaseSensitive = false;
/* Instaniate the sql command */
_cmd = new SqlCommand();
/* Assign the sql connection to the sql command */
_cmd.Connection = _Conn;
/* Define the sql command */
_cmd.CommandText = "SELECT [userId]" +
",[password]" +
",[nextChg]" +
",[changedBy]" +
",[admin]" +
",[userName]" +
" FROM [dbo].[chkUsers]" +
" ORDER BY [userId]";
/* Instantiate the data adapter */
_da = new SqlDataAdapter();
/* Assign the data command for data adapter */
_da.SelectCommand = _cmd;
/* Assign a table name to the data adapter */
_da.TableMappings.Add("Table", "TableName");
/* Fill the data adapter with data */
_da.Fill(_ds);
/* Instantiate datgridview to display data */
DataGridView dgvdataGridView = new DataGridView();
/* Add the datagridview to the winform */
this.Controls.Add(dgvdataGridView);
/* Set properties of dgvDataGridView */
//dgvdataGridView.ColumnCount = 6;
dgvdataGridView.EditMode = DataGridViewEditMode.EditOnEnter;
dgvdataGridView.ReadOnly = false;
dgvdataGridView.RowHeadersVisible = false;
dgvdataGridView.DataSource = _ds.Tables["TableName"].DefaultView;
dgvdataGridView.Columns[0].Width = 50;
dgvdataGridView.Columns[0].HeaderText = "User ID";
dgvdataGridView.Columns[1].Width = 100;
dgvdataGridView.Columns[1].HeaderText = "Password";
dgvdataGridView.Columns[2].Width = 100;
dgvdataGridView.Columns[2].HeaderText = "Last Changed Date";
dgvdataGridView.Columns[3].Width = 50;
dgvdataGridView.Columns[3].HeaderText = "Changed By";
dgvdataGridView.Columns[4].Width = 10;
dgvdataGridView.Columns[4].HeaderText = "Admin";
dgvdataGridView.Columns[5].Width = 200;
dgvdataGridView.Columns[5].HeaderText = "User Name";
}
catch (Exception ex)
{
MessageBox.Show("An unexpected error occured in User Maintenance : " + ex.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
throw ex;
}
}
Please see:
https://stackoverflow.com/questions/52444276/update-insert-data-from-bounded-datagridview-from-datatable
Essentially you need to specify the relevant data command (Insert, update, or delete) as application requirements dictate.