简体   繁体   中英

c# datagridview datasource

I am creating a Datagridview programmatically in a dll file. It's datasource is a Datatable, and my code is as such:

DataGridView dgv = new DataGridView();
DataSet ds = new DataSet();
ds.ReadXml(rdr);
DataTable dt = ds.Tables[0];

dgv.DataSource = dt;

Why then when I check how many columns and rows the datagrid has, it shows as nothing. Although, when I do the same check on the Datatable it shows that there is data. Does the gridview need to be actually on a form for it to be populated?

Thanks.

Apparently it does. I created a new WinForms app, copied your code into the Form_Load event, and added these two lines immediately after your code and got results.

this.Controls.Add(dgv);
MessageBox.Show(dgv.Rows.Count.ToString()); 

If I comment out the first line the count is 0.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM