Firstly, this part of your code seems to be unnecessary:
foreach (DataColumn dc in userTable.Columns)
{
DataGridViewTextBoxColumn column = new DataGridViewTextBoxColumn();
column.DataPropertyName = dc.ColumnName;
column.HeaderText = dc.ColumnName;
column.Name = dc.ColumnName;
column.SortMode = DataGridViewColumnSortMode.Automatic;
column.ValueType = dc.DataType;
userDataGridView.Columns.Add(column);
}
because you are using all of the columns from
userTable
. If you only wanted a few of them, then that would be a reasonable way to do it. The DataGridView will automatically add the columns for you, unless you have set its
<code>
AutoGenerateColumns property to false.
Secondly, your code does not show where the DataGridview has its DataSource property set (except near the top, where it is set to
null
).
Still, wherever that is done try this.
Add a
BindingSource
component to your form, (for the purpose of this explanation I'll call it
userBindingSource
). In the designer, set the DataSource for your DataGridView to this new userBindingSource. From here on you will never change this, all future changes will be done to userBindingSource.
Then wherever in your code you set the DataSource property of userDataGridView, e.g.
userDataGridView.DataSource = null;
userDataGridView.DataSource = userTable;
change those to:
userBindingSource.DataSource = null;
userBindingSource.DataSource = userTable;
Make sure that you change all of them, otherwise it won't work.
Then, assuming that your application still works as it does now, you will be able to use the
BindingSource.Find[
^] method to locate the index of the row, and set
CurrentRow
for the DataGridView to that index.
BindingSource also has
MoveFirst
,
MoveLast
,
MoveNext
and
MovePrevious
methods which will fit the buttons that you have in your app.