Fetch Records in DataGrid

Step 1: Firstly create a database in SQL Server 2008.

Example: db2

Step 2: create table in that database.

Example: emp

image-1.jpg

Step 3: Open VS 2010. Then new project -> Windows Form Application.

Step 4: Design this format

image-2.jpg

Step 5: Firstly create connection and show the table in DataGrid:

Add namespace Using System.Data.Sqlclient.

namespace
WindowsFormsApplication1
{
    public partial class Form1 : Form

    {

        public Form1()

        {

            InitializeComponent();

        }

        SqlDataAdapter da;

        DataSet ds;

        DataRow dr;

 

        private void button1_Click(object sender, EventArgs e)

        {

            da = new SqlDataAdapter("select * from emp1", "database=db2; server=LENOVO-PC\\SQLEXPRESS; Integrated Security=True");

            ds = new DataSet();

            da.Fill(ds);

            dataGridView1.DataSource = ds.Tables[0];

        }

 

Step 6: Then we want 1st record of table in textboxes, so write this code:

private void btnFirst_Click(object sender, EventArgs e)

{

    int i = 0;

    textBox1.Text = ds.Tables[0].Rows[i][0].ToString();

    textBox2.Text = ds.Tables[0].Rows[i][1].ToString();

    textBox3.Text = ds.Tables[0].Rows[i][2].ToString();

}

  
Step 7: for next record, write this code

private void btnNxt_Click(object sender, EventArgs e)

{

     int i;

     i++;

     if (i < ds.Tables[0].Rows.Count)

     {                 

            textBox1.Text = ds.Tables[0].Rows[i][0].ToString();

            textBox2.Text = ds.Tables[0].Rows[i][1].ToString();

            textBox3.Text = ds.Tables[0].Rows[i][2].ToString();

      }

      else

      {

           MessageBox.Show("This is Your Last Record");

      }           

}

 

Step 8: for previous record, write this code:

private void btnprevious_Click(object sender, EventArgs e)

{

     int i;

     i--;

     if (i == 0)

     {

        textBox1.Text = ds.Tables[0].Rows[i][0].ToString();

        textBox2.Text = ds.Tables[0].Rows[i][1].ToString();

        textBox3.Text = ds.Tables[0].Rows[i][2].ToString();

     }

     else

     {

          MessageBox.Show("This is Your first Record");

     }           

}

  
Step 9: for last record, write this code:

private void btnLast_Click(object sender, EventArgs e)

{

    int i;

    i = ds.Tables[0].Rows.Count - 1;

    textBox1.Text = ds.Tables[0].Rows[i][0].ToString();

    textBox2.Text = ds.Tables[0].Rows[i][1].ToString();

    textBox3.Text = ds.Tables[0].Rows[i][2].ToString();

}

Ebook Download
View all
Learn
View all