Rekcs
Rekcs

Reputation: 887

Loading data into DataGridView in C#

I am trying to add values from Win32_SystemDriver into a DataGridView, I it will load until it finishes. When it ends up loading all the data it will change all the rows for the last value from the query. This is the code:

ObjectQuery query8 = new ObjectQuery("SELECT * FROM Win32_SystemDriver"); 

ManagementObjectSearcher searcher8 = 
    new ManagementObjectSearcher(scope, query8);

foreach (ManagementObject queryObj in searcher8.Get())
{
    DataTable dt = new DataTable();
    dt.Columns.Add("Descrição");
    foreach (DataGridViewRow oItem in dataGridView1.Rows)  
    {
        dt.Rows.Add(new object[] { queryObj["Description"] });
    }
    dataGridView1.DataSource = dt;
}

What it's wrong about this code? Why after loading every data it will change every row to the last value from the query?

This is how I solve it by myself:

ObjectQuery query8 = new ObjectQuery("SELECT * FROM Win32_SystemDriver"); 

ManagementObjectSearcher searcher8 = 
    new ManagementObjectSearcher(scope, query8);

DataTable dt = new DataTable();
dt.Columns.Add("Descrição");

foreach (ManagementObject queryObj in searcher8.Get())
{
    dt.Rows.Add(new object[] { queryObj["Description"] });
}

dataGridView1.DataSource = dt;

Upvotes: 0

Views: 158

Answers (1)

Mong Zhu
Mong Zhu

Reputation: 23732

The problem is that at each iteration you create a new DataTable, which you populate and assign as DataSource. At the next iteration you repeat this process and erase the information from before. Therefore you end up at the last iteration with only the last entry.

Another problem is you inner loop. After assigning the first time dataGridView1.DataSource = dt; it will have 1 row, so you can add 1 element to your DataTable at the next iteration it will be 2 and so on.

You need to move the declaration of the DataTable and the setting of the DataSource outside of the outer loop and remove the inner loop

DataTable dt = new DataTable();
dt.Columns.Add("Descrição");

foreach (ManagementObject queryObj in searcher8.Get())
{    
    dt.Rows.Add(new object[] { queryObj["Description"] });
}
dataGridView1.DataSource = dt;

Upvotes: 1

Related Questions