Masoud Masoud - 1 month ago 6
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();
this.DisplayCustomer();
this.AllCustomer();
}
}

private void AllCustomer()
{

DataTable dt = new DataTable();

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


if (dt != null)
{

grvCustomer.Visible = true;

grvCustomer.DataSource = dt;

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

}
}

Answer

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.ClearSelection();
this.grvCustomer.Rows[lastRowIndex].Selected = true;
this.grvCustomer.FirstDisplayedScrollingRowIndex = lastRowIndex;

EDIT:

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;
        break;
    }
}
Comments