Reputation: 10644
I have a datagridview bind to a datatable through datagridview's datasource property. Rows are added one by one and always at the datagridview's top using below line of code, for example:
DataRow newRow = myDataTable.NewRow();
newRow[0] = "column1 value";
newRow[1] = "column2 value";
myDataTable.Rows.InsertAt(newRow, 0);
The problem is that datagridview vertical scroll moves down making not visible the last row added at the top of the datagridview so I do not want vertical scroll to move down in order to make visible last row inserted at top.
How can I do this?
ATTEMPT 1:
DataGridViewRow selectedRow = null;
if (dataGridView1.SelectedRows.Count > 0)
selectedRow = dataGridView1.SelectedRows[0];
DataRow newRow = myDataTable.NewRow();
newRow[0] = "column1 value";
newRow[1] = "column2 value";
myDataTable.Rows.InsertAt(newRow, 0);
if (selectedRow != null)
dataGridView1.FirstDisplayedScrollingRowIndex = selectedRow.Index;
else
dataGridView1.FirstDisplayedScrollingRowIndex = 0;
extracted from here.
Seems not working. dataGridView1.FirstDisplayedScrollingRowIndex always is 0 but datagridview continues scrolling down.
Upvotes: 0
Views: 662
Reputation: 98
FirstDisplayedScrollingRowIndex
will work if you work with datagridview on direct.
For example:
Form1.cs
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
dataGridView1.Columns.Add("firstColumn", "Name");
dataGridView1.Columns.Add("secondColumn", "Mark");
dataGridView1.Rows.Add(99);
for (int i = 99; i >= 0; i--)
{
dataGridView1[0, i].Value = "column1 value " + (100 - i);
dataGridView1[1, i].Value = "column2 value " + (100 - i);
}
dataGridView1.FirstDisplayedScrollingRowIndex = 0;
}
}
Result
Upvotes: 0
Reputation: 700
You only need to scroll to the top of the DataGridView each time you add a new row. You can do so by setting the property FirstDisplayedScrollingRowIndex to the very first row which has the index 0:
dataGridView.FirstDisplayedScrollingRowIndex = 0;
Upvotes: 2