Masoud Masoud - 1 year ago 71
C# Question

How DataGridView selector goes to particular record

After adding a customer record, i call a function that shows all customers in DataGridView and it selects first row in DataGridView .

now i would like my populated DataGridView goes to customerid just now has been added. Now added record is in my DataGridView and is in the end of list and the first record has been selected from DataGridView .

private void btnAdd_Click(object sender, EventArgs e)
frmAddModifyCustomer addCustomerForm = new frmAddModifyCustomer();
addCustomerForm.addCustomer = true;
DialogResult result = addCustomerForm.ShowDialog();
if (result == DialogResult.OK)
customer = addCustomerForm.customer;
txtCustomerID.Text = customer.CustomerID.ToString();

private void AllCustomer()

DataTable dt = new DataTable();

dt = CustomerDB.AllCustomer();
catch (Exception ex)
MessageBox.Show(ex.Message, ex.GetType().ToString());

if (dt != null)

grvCustomer.Visible = true;

grvCustomer.DataSource = dt;

MessageBox.Show("No customer found with this ID. " +
"Please try again.", "Customer Not Found");
grvCustomer.Visible = false;


Answer Source

As I understand you would like to select the newly added row on the bottom of the grid.

Optionally you can clear the previous selection if any exists. Set the selected property of the last row to true. And again optionally scroll grid's view to the last row of the grid, in case it is outside of the visible grid's region.

var lastRowIndex = this.grvCustomer.Rows.Count - 1;

this.grvCustomer.Rows[lastRowIndex].Selected = true;
this.grvCustomer.FirstDisplayedScrollingRowIndex = lastRowIndex;


In case the modified row is not known, you have to enumerate through the rows collection and find the value of the cell under the customer ID column that match the value of the dialog form.

foreach (DataGridViewRow row in this.grvCustomer.Rows)
    if (row.Cells["CustomerID"].Value.ToString() == addCustomerForm.customer.CustomerID.ToString())
        row.Selected = true;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download