This is my code:
private void getData(string selectCommand)
{
string connectionString = @ "Server=localhost;User=SYSDBA;Password=masterkey;Database=C:\data\test.fdb";
dataAdapter = new FbDataAdapter(selectCommand,
connectionString);
DataTable data = new DataTable();
dataAdapter.Fill(data);
bindingSource.DataSource = data;
}
private void button1_Click(object sender, EventArgs e)
{
getData(dataAdapter.SelectCommand.CommandText);
}
private void Form1_Load(object sender, EventArgs e)
{
dataGridView1.DataSource = bindingSource;
getData("SELECT * FROM cities");
}
After reload data on button1 click event, cell selection jumps on first column and scrollbars is reset. How to save position of DataGridView?
Here's the solution I came up with. Doesn't require a row to be selected and puts the scrollbar back in the same area after the refresh, provided that the number of rows doesn't vary greatly.
int saveRow = 0;
if (dataGridView1.Rows.Count > 0 && dataGridView1.FirstDisplayedCell != null)
saveRow = dataGridView1.FirstDisplayedCell.RowIndex;
dataGridView1.DataSource = dataTable1;
if (saveRow != 0 && saveRow < dataGridView1.Rows.Count)
dataGridView1.FirstDisplayedScrollingRowIndex = saveRow;
int FirstDisplayedScrollingRowIndex = this.dgvItems.FirstDisplayedScrollingRowIndex; //Save Current Scroll Index
int SelectedRowIndex = 0;
if (this.dgvItems.SelectedRows.Count > 0) SelectedRowIndex = this.dgvItems.SelectedRows[0].Index; //Save Current Selected Row Index
//REFRESH DataGridView HERE
if ((FirstDisplayedScrollingRowIndex >=0) && ((this.dgvItems.Rows.Count -1) >= FirstDisplayedScrollingRowIndex)) this.dgvItems.FirstDisplayedScrollingRowIndex = FirstDisplayedScrollingRowIndex; //Restore Scroll Index
if ((this.dgvItems.Rows.Count -1) >= SelectedRowIndex) this.dgvItems.Rows[SelectedRowIndex].Selected = true; //Restore Selected Row
You could save selected row before launching getData, using DataGridView.CurrentRow
, and select that row after the Grid has been loaded.
In this question I answered how to select an specific row in a DataGridView.
Edit: I supposed that you are using WinForms
Edit2: And what about scrollbars?
You can save the first visible row index, too with this statement
DataGridView.FirstDisplayedCell.RowIndex
The easy way is Blow code:
int CurrentRowIndex = (hSuperGrid1.CurrentRow.Index);
////after Fill The DataGridView
hSuperGrid1.ClearSelection();
hSuperGrid1.CurrentRow.Selected = false;
hSuperGrid1.Rows[CurrentRowIndex].Selected = true;
hSuperGrid1.CurrentCell = hSuperGrid1[0, CurrentRowIndex];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With