I've tried everything using other answers on the forum. I simply want my data grid view to dynamically update when i select the update button on my form after making a change.
Ref the code below, the current result is that when I add a new row and press the update button, the data grid view simply appends all existing records (and the new row) underneath so the list keeps growing in size with duplicate values.
public UserGroupsGridViewForm()
{
InitializeComponent();
}
private void UserGroupsGridViewForm_Load(object sender, EventArgs e)
{
LoadUserGroupsToDataTable();
}
public static SqlCommandBuilder userGroupsSqlCommandBuilder;
public static DataTable userGroupsDataTable = new DataTable();
public static SqlDataAdapter userGroupsSqlAdaptor;
public void LoadUserGroupsToDataTable()
{
try
{
SqlConnection connection = new SqlConnection(connectionString);
string cmdText1 = "SELECT * FROM [dbo].[UserGroups]";
userGroupsSqlAdaptor = new SqlDataAdapter(cmdText1, connection);
userGroupsSqlCommandBuilder = new SqlCommandBuilder(userGroupsSqlAdaptor);
userGroupsSqlAdaptor.Fill(userGroupsDataTable);
}
catch (Exception ex)
{
log.Error(ex);
SystemEvents.DatabaseExceptions(ex);
}
LoadDataTabletoGridView();
}
private void LoadDataTabletoGridView()
{
try
{
UserGroupsGridView1.DataSource = userGroupsDataTable;
}
catch (Exception ex)
{
SystemEvents.DatabaseExceptions(ex);
}
}
private void SaveChangesButton_Click(object sender, EventArgs e)
{
userGroupsSqlAdaptor.Update(userGroupsDataTable);
//UserGroupsGridView1.Update(); // not working!
//UserGroupsGridView1.Refresh(); // not working!
LoadUserGroupsToDataTable();
}