How to view WMI queries in a dataset.

The following sample code demonstrates putting WMI WQL queries into a DataSet and displaying it in a datagridview.

This could become the basis of a really powerful system management utility. 

 

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

using System.Management;

namespace WMIForm
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            WMIQuery(“SELECT * FROM Win32_Service”);           
        }

        private void WMIQuery(string query)
        {
            SelectQuery qry = new SelectQuery(query);

            DataSet ds = new DataSet();
            DataTable Table = ds.Tables.Add(“WMI”);

            ManagementObjectSearcher ms = new ManagementObjectSearcher(qry);
            ManagementObjectCollection mc = ms.Get();

            Boolean loaded = false;

            foreach (ManagementObject mo in ms.Get())
            {
                if (!loaded)
                {
                    foreach (PropertyData prop in mo.Properties)
                    {
                        Table.Columns.Add(prop.Name);
                    }
                    loaded = true;
                }
                DataRow row = Table.NewRow();
                foreach (PropertyData prop in mo.Properties)
                {
                    row[prop.Name] = prop.Value;
                }
                Table.Rows.Add(row);
            }

            dataGridView1.DataSource = Table;
        }

        private void GoButton_Click(object sender, EventArgs e)
        {
            WMIQuery(QueryTextBox.Text);
        }
    }
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s