简体   繁体   中英

How to display WMI data in a DataGridView

I am trying to display some data in DataGridView but it's not being displayed. I then tried displaying it in a ListBox and it works. How I can I get it to work in the DataGridView .

   ManagementClass mc = new ManagementClass("Win32_Service");

    foreach (ManagementObject mo in mc.GetInstances())
       {
           listBox1.Items.Add(mo["Name"].ToString());
           listBox2.Items.Add(mo["Description"].ToString());
           listBox3.Items.Add(mo["DispalyName"].ToString());
           listBox4.Items.Add(mo["ServiceType"].ToString());

       }       

Thanks

In your DataGridView you have to add at least four columns to display the results.

  ManagementClass mc = new ManagementClass("Win32_Service");

  grid.Columns.Add(new DataGridViewTextBoxColumn());
  grid.Columns.Add(new DataGridViewTextBoxColumn());
  grid.Columns.Add(new DataGridViewTextBoxColumn());
  grid.Columns.Add(new DataGridViewTextBoxColumn());

  foreach (ManagementObject mo in mc.GetInstances())
  {
    object col1 = mo["Name"] != null ? mo["Name"].ToString() : null;
    object col2 = mo["Description"] != null ? mo["Description"].ToString() : null;
    object col3 = mo["DisplayName"] != null ? mo["DisplayName"].ToString() : null;
    object col4 = mo["ServiceType"] != null ? mo["ServiceType"].ToString() : null;

    grid.Rows.Add(new object[] { col1, col2, col3, col4 });
  }

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