populating a datatable with odbcdatareader

R

Ricardo Luceac

HI all..

I have a huge table that I want to display in a datagrid, the problem is
that if I make a dataset, the entire table must go to the dataset to the
data begin to display, and it takes much time...

I need to start show data after a row pushed to the dataset, so I think
of using the datareader to populate a datatable and bind the datatable
to the datagrid.

But I don't know how to do this...

Can someone help me??

[]s...
 
A

Angel J. Hernández M.

Why would you like to show all of those records? However you can implemenet
something like this...

// Class' Member
private DataTable m_table = new DataTable();

// Form's Load
private void Form1_Load(object sender, System.EventArgs e) {
m_table.Columns.AddRange(new DataColumn[] {new DataColumn("customerid",
typeof(System.String)),
new
DataColumn("companyname", typeof(System.String)),
new
DataColumn("contactname", typeof(System.String))});
}



// This code does what you want
private void button2_Click(object sender, System.EventArgs e) {
SqlDataReader rdr = null;
object[] values = new object[3];

using(SqlConnection conn = new SqlConnection("Data Source=(local);User
ID=sa;Password=;Initial Catalog=Northwind")) {
try {
SqlCommand cmd = new SqlCommand("select customerid, companyname,
contactname from customers", conn);
conn.Open();
rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection);

while(rdr.Read()) {
rdr.GetValues(values);
m_table.Rows.Add(values);
m_table.AcceptChanges();
dataGrid1.SetDataBinding(m_table, null);
}
}
catch (Exception ex) {System.Diagnostics.Trace.WriteLine(ex.Message);}
finally {
if (rdr != null) rdr.Close();
}
}
}

I can suggest one more thing, if this table is so huge then implement a
threading mechanism to load and refresh the DataGrid so your form won't
look "blank"
when you select it.


Regards,
 
R

Ricardo Luceac

OK, thanks...

But if I don't know how many columns and the data type that it holds???


[]s...
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top