Masoud Masoud - 1 month ago 9
C# Question

how gridview selector goes to particular record

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

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

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();

}

}


public static DataTable AllCustomer()
{
SqlConnection connection = MMABooksDB.GetConnection();
string selectStatement
= "SELECT CustomerID, Name, Address, City, State, ZipCode "
+ "FROM Customers";

SqlCommand selectCommand =
new SqlCommand(selectStatement, connection);


try
{
connection.Open();
SqlDataReader custReader =
selectCommand.ExecuteReader();
if (custReader.HasRows)
{
DataTable dt = new DataTable();
dt.Load(custReader);
return dt;
}
else
{
return null;
}
}
catch (SqlException ex)
{
throw ex;
}
finally
{
connection.Close();
}
}

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