reddevil54
reddevil54

Reputation: 53

How do i add a previous and next button to datagridview

I am using Visual studio 2012 and have made a windows form application, for one of the forms I am using a datagridview which shows the information of a table from the SQL database.

I have made the form load information from the datagridview rows directly into a textbox automatically.

SqlDataAdapter SDA = new SqlDataAdapter("SELECT * FROM Stock", con);
DataTable DATA = new DataTable();
SDA.Fill(DATA);
dataGridView1.DataSource = DATA

txtStock3.Text = dataGridView1.SelectedRows[0].Cells[0].Value.ToString();
Descriptioncombo2.Text = dataGridView1.SelectedRows[0].Cells[1].Value.ToString();
txtprice2.Text = dataGridView1.SelectedRows[0].Cells[2].Value.ToString();

The problem is that I need to add a previous button and a next button so that users can navigate through the datagridview rows and see the information in a textbox from each column of a datagridview row. I have looked at similar questions and have browsed through the internet to look for a solution to my problem but i can't seem to find a way which works with my code. Also could you tell me how to add a line of code which tells the user that there is no more rows to select if they click next through all rows of the database.

Upvotes: 0

Views: 9113

Answers (4)

karam abdellah
karam abdellah

Reputation: 21

//first

int i = 0;
  this.dataGridView1.CurrentCell = dataGridView1.Rows[0].Cells[dataGridView1.CurrentCell.ColumnIndex];


//prev 

  int prev = dataGridView1.CurrentRow.Index - 1;
            if (prev >= 0)
            {
                this.dataGridView1.CurrentCell = dataGridView1.Rows[prev].Cells[dataGridView1.CurrentCell.ColumnIndex];
                //MessageBox.Show(dataGridView1[0, dataGridView1.CurrentRow.Index].Value.ToString());
            }


//next
     int next = dataGridView1.CurrentRow.Index + 1;
            if (next < dataGridView1.Rows.Count)
            {
                this.dataGridView1.CurrentCell = dataGridView1.Rows[next].Cells[dataGridView1.CurrentCell.ColumnIndex];
                //MessageBox.Show(dataGridView1[0, dataGridView1.CurrentRow.Index].Value.ToString());
            }
//last
     int i = dataGridView1.Rows.Count - 1;
            if (i < dataGridView1.Rows.Count)
            {
                this.dataGridView1.CurrentCell = dataGridView1.Rows[i].Cells[dataGridView1.CurrentCell.ColumnIndex];
                //MessageBox.Show(dataGridView1[0, dataGridView1.CurrentRow.Index].Value.ToString());
            }

Upvotes: 2

OhBeWise
OhBeWise

Reputation: 5454

As an alternate to Karen's solution, if you prefer/must go with buttons to navigate then you'll want to handle the CurrentCellChanged event as well as the following button Click events:

private void DataGridView1_CurrentCellChanged(object sender, EventArgs e)
{
    if (this.dataGridView1.CurrentRow != null)
    {
        txtStock3.Text = dataGridView1.CurrentRow.Cells[0].Value.ToString();
        Descriptioncombo2.Text = dataGridView1.CurrentRow.Cells[1].Value.ToString();
        txtprice2.Text = dataGridView1.CurrentRow.Cells[2].Value.ToString();

        this.prevButton.Enabled = this.dataGridView1.CurrentRow.Index > 0;
        this.nextButton.Enabled = this.dataGridView1.CurrentRow.Index < this.dataGridView1.Rows.Count - 1;
    }
}

private void PrevButton_Click(object sender, EventArgs e)
{
    int prev = this.dataGridView1.CurrentRow.Index - 1;
    this.dataGridView1.CurrentCell = this.dataGridView1.Rows[prev].Cells[this.dataGridView1.CurrentCell.ColumnIndex];
}

private void NextButton_Click(object sender, EventArgs e)
{
    int next = this.dataGridView1.CurrentRow.Index + 1;
    this.dataGridView1.CurrentCell = this.dataGridView1.Rows[next].Cells[this.dataGridView1.CurrentCell.ColumnIndex];
}

The CurrentCellChanged event will handle logic for if you can click Previous or Next. Their respective click events simply move the current cell backwards or forwards one row.

Upvotes: 1

Karen Payne
Karen Payne

Reputation: 5157

One way to provide navigation is by using a BindingNavigator where you can remove unnecessary buttons and for TextBox you can data binding.

Code responsible for loading data. Replace the console.writeline in the catch as you see fit e.g. write to a log file etc.

public class DataOperations
{
    public DataTable LoadCustomers()
    {
        DataTable dtCustomers = new DataTable();

        using (SqlConnection cn = new SqlConnection(Properties.Settings.Default.ConnectionString))
        {
            string commandText = @"SELECT [Identfier], [CompanyName],[ContactName],[ContactTitle] FROM [NORTHWND1.MDF].[dbo].[Customers]";

            using (SqlCommand cmd = new SqlCommand(commandText, cn))
            {
                try
                {
                    cn.Open();
                    dtCustomers.Load(cmd.ExecuteReader());
                    dtCustomers.Columns["Identfier"].ColumnMapping = MappingType.Hidden;
                    dtCustomers.Columns["ContactTitle"].ColumnMapping = MappingType.Hidden;
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
            }
        }

        return dtCustomers;
    }
}

On a form, one BindingNavigator, one dataGridView, one TextBox

DataOperations dataOps = new DataOperations();
BindingSource bsCustomers = new BindingSource();
bsCustomers.DataSource = dataOps.LoadCustomers();
dataGridView1.DataSource = bsCustomers;
bindingNavigator1.BindingSource = bsCustomers;
txtContactTitle.DataBindings.Add("Text", bsCustomers, "ContactTitle");

An alternate to the BindingNavigator is to make the BindingSource form level, private variable. Then in buttons call BindingSource.Move method e.g. bsCustomers.MoveFirst(). Of course there is MoveNext, MoveLast and MovePrevious too.

Upvotes: 4

user853710
user853710

Reputation: 1767

You configure the comulmns in the grid to be your matching types. Then after the query you bind the data to this gridView. You add two buttons where the "next" button will fetch the currentselectedrow of the grid, and set it's follower to be the selected one. previous will do the opposite. This is a small pain in the ass. I hate grids in WinForms. The last 4 years, since I did not see them, have been the happiest years of my lif

Upvotes: 1

Related Questions