One of the most questions asked to me, how to fill dataGridview Using DataReader, if you note the behavior of DataReader you will note that when you read using DataReader you read row by row so you 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. Step1: Create class that contains properties Step 2: create ArrayList to represent your store Step 3: When you retrieve do the followingIntroduction
Using the Code
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; } } }
ArrayList sequence = new ArrayList();
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;
The Final Code
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(); }
الأحد، 14 ديسمبر 2008
dataGridview Using DataReader
Collapse
Collapse
Collapse
Collapse
0 التعليقات:
إرسال تعليق