Hi,
I need to fill my datagridview in csharp using datareader, how i do it?
Loading
Know the answer? Post it. Somebody with the same question will find it here.
Answer a question in the forums and earn +20 SHARP for every answer.
See unanswered questions
DevSocialUpcoming · 3rd editionAI Agents ConferenceDec 1–3, 2026Live onlineFree to attend5days leftRegister
Priya LingeRank #785 · 2.9K reputationPosted Aug 29, 2011, 10:05 PM EDT
You can fill datagridView using datareder as following way,
public void getdata()
{
ArrayList arrlist = new ArrayList();
DataGridView myDataGrid = new DataGridView();
sqlConnection.Open();
string query = "select * from Customer";
sqlCommand = new SqlCommand(query, sqlConnection);
sqlReader = sqlCommand.ExecuteReader();
while (sqlReader.Read())
{
Customerdetails cus = new Customerdetails();
cus.Id =Convert.ToInt32(sqlReader[0].ToString());
cus.Name = sqlReader[1].ToString();
arrlist.Add(cus);
}
myDataGrid.DataSource = arrlist;
myDataGrid.Show();
panel1.Controls.Add(myDataGrid);
}
Here we have one class name Customerdetails
class Customerdetails
{
private string name;
private int id;
public string Name
{
get { return name; }
set { name = value; }
}
public int Id
{
get { return id; }
set { id = value; }
}
}
Hope this will help you.
Thanks.
Jiteendra SampathiraoRank #585 · 4.1K reputationPosted Aug 29, 2011, 10:13 PM EDT
void Page_Load(Object sender, EventArgs e)
{
String Qry;
Sqlcommand cmd;
SqlDataReader dr;
SqlConnection conn = new SqlConnection(ConfigurationManager.AppSettings["sqlserver"]);
conn.Open();
Qry = "select a,b,c,d from your_table_name";
cmd= New Sqlcommand(Qry, conn);
dr = cmd.ExecuteReader();
Gridview1.DataSource = dr;
Gridview1.DataBind();
}
Black Diamond191 reputationPosted Aug 29, 2011, 10:18 PM EDT
Thank you for your code, it works.....