MY PRINCIPAL :- "THE GLORY OF LIFE ID TO LOVE NOT TO BELOVED...TO GIVE NOT TO GET..TO SERVE NOT TO BE SERVED."

Saturday, November 20, 2010

Working With DataReader In Ado.Net

As we know the datareader is a forward only and read only..so we can navigate through records in an forward manner not in backward. Here is the code to perform navigation in datareader. After this post we are going to see how to navigate the records in dataset and CRUD operations..

Design:








Coding:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using System.Data.SqlClient;
namespace datareadernext
{
    public partial class Form1 : Form
    {
        private SqlConnection con;
        private SqlDataReader dr;
        private SqlCommand cmd;
        public Form1()

        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            string strcon = @"Data Source=.;Initial Catalog=PracticeDB;Persist Security Info=True;User ID=sa;Password=123";
            con = new SqlConnection(strcon);
            cmd = new SqlCommand();
            cmd.Connection = con;
            cmd.CommandType = CommandType.Text;
            cmd.CommandText = "select * from sample";
            if (con.State == ConnectionState.Closed)
                con.Open();
            dr = cmd.ExecuteReader();
          //  con.Close();
            showrecord();
           
        }

        private void showrecord()
        {
            if (dr.Read())
            {
                textBox1.Text = dr.GetValue(0).ToString();
                textBox2.Text = dr.GetValue(1).ToString();
                textBox3.Text = dr.GetValue(2).ToString();
                textBox4.Text = dr.GetValue(3).ToString();

            }
            else
            {
                MessageBox.Show("no further record...");
            }

        }

        private void button1_Click(object sender, EventArgs e)
        {
            showrecord();
        }
    }
}

No comments:

Post a Comment