mobile ads

Friday 11 October 2013

DataGridView using DataReader

Solution 1
DataReader will read row by row so you make looping to read all records if you want to display all record or any element from record , in other hand dataGridview need to take all data of your records in one package, so the solution is to make centralize store by make class that contains properties and set value for each properties when you read the value of each record and store each object from class that you create in ArrayList so the ArrayList will represent your store.

1.Create a class that contains properties
public class MyDetails
    {
        private int age;

        public int Age
        {
            get { return age; }
            set { age = value; }
        }
        private string name;

        public string Name
        {
            get { return name; }
            set { name = value; }
        }

        private int id;

        public int Id
        {
            get { return id; }
            set { id = value; }
           } 
        }
 
2. Create ArrayList to represent data


ArrayList sequence = new ArrayList();
 
3. Retreive data

SqlConnection sqlCon = null;
            try
            {
                sqlCon = new SqlConnection();
                sqlCon.ConnectionString = "Your Connection String";
                SqlCommand cmd = new SqlCommand();
                cmd.Connection = sqlCon;
                cmd.CommandText = "SELECT * FROM StudentInfo";
                sqlCon.Open();
                SqlDataReader reader = cmd.ExecuteReader();
                while (reader.Read())
                {
                    MyDetails m = new MyDetails();
                    m.Id = (int)reader[0];
                    m.Name = reader[1].ToString();
                    m.Age = (int)reader[2];
                    sequence.Add(m);
                }
                dataGridView1.DataSource = sequence;
            }
            finally
            {
                sqlCon.Close();
            } 
 

Solution 2

SqlConnection con = new SqlConnection("Connection String");
con.Open();

SqlCommand com = new SqlCommand("SQL Query", con);
SqlDataReader read = com.ExecuteReader();
DataSet ds = new DataSet();
DataTable dt = new DataTable("Table1");
ds.Tables.Add(dt);
ds.Load(read, LoadOption.PreserveChanges, ds.Tables[0]);

gridControl1.DataSource = ds.Tables[0];
 

0 comments:

Post a Comment