0

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;

1 Answer 1

1

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;
Sign up to request clarification or add additional context in comments.

9 Comments

If I do that it displays an error saying: "A column named 'Descrição' already belongs to this DataTable"
@Rekcs Do you want to have only 1 column for all ManagementObject queries ?
@Rekcs then you should probably move it also outside the loop. I edited my answer
I want only a column, yes. I've changed with your code and it won't give me any error but does not displays values from ManagementObject
@Rekcs but it did display them before?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.