Hi @Darryl Hoar , Welcome to Microsoft Q&A,
In your code, the DataGridView is bound to a DataTable, and the user can edit data in the DataGridView. However, the DataTable does not appear to update with the user's input. This may be because the DataGridView has not yet committed its edited values to the underlying DataTable.
You can ensure that the DataGridView's changes are committed to its data source by calling the DataGridView's EndEdit() method. You can commit changes manually before data is saved or before other logic operations.
public DataTable load_locations()
{
DataTable dt = new DataTable();
string selectCommand = "SELECT loccode1, description FROM location ORDER BY loccode1 ASC";
SqlDataAdapter da = new SqlDataAdapter(selectCommand, connectionString);
da.SelectCommand.CommandTimeout = 120;
da.Fill(dt);
dt.Columns.Add("newlocation", typeof(int)); // Add new column for user input
return dt;
}
private void Form1_Load(object sender, EventArgs e)
{
locationsDGV.DataSource = load_locations();
// Hook up the CellValueChanged event
locationsDGV.CellValueChanged += locationsDGV_CellValueChanged;
}
private void locationsDGV_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
locationsDGV.EndEdit();
}
private void SaveData()
{
// Ensure the changes in DataGridView are committed to the DataTable
locationsDGV.EndEdit();
locationsDGV.BindingContext[locationsDGV.DataSource].EndCurrentEdit();
DataTable dt = (DataTable)locationsDGV.DataSource;
foreach (DataRow row in dt.Rows)
{
if (row["newlocation"] != DBNull.Value)
{
Console.WriteLine($"User input: {row["newlocation"]}");
}
}
}
Best Regards,
Jiale
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.