- // Place a datagridview control on the form
- // Place five button controls on the form and name them as:
- // FirstRecord, PreviousRecord, NextRecord, LastRecord, Details
- public partial class Form1 : Form
- {
- private int RowIndex = 0;
- public Form1()
- {
- InitializeComponent();
- }
- private void Form1_Load(object sender, EventArgs e)
- {
- dataGridView1.MultiSelect = false;
- dataGridView1.Columns.Add("FirstName", "First Name");
- dataGridView1.Columns.Add("LastName", "Last Name");
- dataGridView1.Columns.Add("Email", "Email");
- object[] row1 = { "John", "Doe", "john.doe@mail.xzy.com"};
- object[] row2 = { "Tom", "Baker", "tom.baker@mail.xzy.com"};
- object[] row3 = { "Suzan", "Carter", "suzan.carter@mail.xzy.com"};
- dataGridView1.Rows.Add(row1);
- dataGridView1.Rows.Add(row2);
- dataGridView1.Rows.Add(row3);
- }
- private void FirstRecord_Click(object sender, EventArgs e)
- {
- RowIndex = 0;
- dataGridView1.Rows[RowIndex].Selected = true;
- }
- private void PreviousRecord_Click(object sender, EventArgs e)
- {
- if (RowIndex >0)
- {
- RowIndex--;
- dataGridView1.Rows[RowIndex].Selected = true;
- }
- }
- private void NextRecord_Click(object sender, EventArgs e)
- {
- int TotalRows = dataGridView1.Rows.Count - 1;
- if (RowIndex < TotalRows)
- {
- RowIndex++;
- dataGridView1.Rows[RowIndex].Selected = true;
- }
- }
- private void LastRecord_Click(object sender, EventArgs e)
- {
- RowIndex = dataGridView1.Rows.Count-1;
- dataGridView1.Rows[RowIndex].Selected = true;
- }
- private void Details_Click(object sender, EventArgs e)
- {
- DataGridViewSelectedRowCollection RowCollection = dataGridView1.SelectedRows;
- foreach ( DataGridViewRow Row in RowCollection)
- {
- string FirstName = Row.Cells[0].Value.ToString();
- string LastName = Row.Cells[1].Value.ToString();
- string Email = Row.Cells[2].Value.ToString();
- MessageBox.Show(String.Format("First Name: {0} \nLast Name: {1} \nEmail: {2}",FirstName, LastName, Email));
- }
- }
- }
C# - Navigate Rows In DataGridView
This code snippet allows you to navigate through a DataGridView control. The navigation buttons select a row and the details button gets the values for the currently selected row and displays it in a message box.
1 comment:
thank's
Post a Comment