首页 > 解决方案 > 将 WMI 结果绑定到 datagridview

问题描述

我搜索了一段时间以来的答案,但我没有找到任何符合我需要的答案。

我的问题如下:我提出了一些 wmi 请求来检索有关远程计算机的一些信息。但我希望其中一些信息显示在 datagridview 上。我不知道如何以 promatic 方式填充我的 datagridview。

我的请求非常简单,我的结果正确显示在控制台上:它显示已安装的软件,以及一些需要的信息。

 public void getInstalledSoftwares(string hostname)
    {
        ManagementScope scope = new ManagementScope("\\\\" + hostname + "\\root\\cimv2");
        scope.Connect();

        ObjectQuery query = new ObjectQuery("SELECT * FROM Win32_Product");
        ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, query);

        foreach (ManagementObject product in searcher.Get())
        {

            Object Name = product["Name"].ToString();
            Object Version = product["Version"].ToString();
            /*
             * [...]
             **/ 

            // Populate the datagridview ?

            Console.WriteLine(Name + " --- " + Version);
        }

    }

启动此请求的按钮在另一个类中本地化。所以我尝试了这样的事情:

Form.mydgv.Rows.add(name);

它告诉我行没有任何定义。然后,我不知道这是否是个好主意,但我的 Datagridview 是“预制”的,带有所需的列,如下所示:

<DataGrid x:Name="datagrid_software"  Margin="5" Grid.Row="1" >
                    <DataGrid.Columns>
                        <DataGridCheckBoxColumn Binding="{x:Null}" ClipboardContentBinding="{x:Null}" Header="Application" Width="*"/>
                        <DataGridCheckBoxColumn Binding="{x:Null}" ClipboardContentBinding="{x:Null}" Header="Editeur" Width="Auto"/>
                        <DataGridCheckBoxColumn Binding="{x:Null}" ClipboardContentBinding="{x:Null}" Header="Installé le" Width="Auto"/>
                        <DataGridCheckBoxColumn Binding="{x:Null}" ClipboardContentBinding="{x:Null}" Header="Localisation" Width="*"/>
                        <DataGridCheckBoxColumn Binding="{x:Null}" ClipboardContentBinding="{x:Null}" Header="Taille" Width="Auto"/>
                        <DataGridCheckBoxColumn Binding="{x:Null}" ClipboardContentBinding="{x:Null}" Header="Version" Width="Auto"/>
                        <DataGridCheckBoxColumn Binding="{x:Null}" ClipboardContentBinding="{x:Null}" Header="Uninstall" Width="*"/>
                    </DataGrid.Columns>
                </DataGrid>

非常感谢你的帮助。

标签: c#datagridviewwmi

解决方案


使用ORMi并将 DataGrid 绑定到结果集合:

var products = helper.Query("SELECT * FROM Win32_Product").ToList();

mydgc.ItemsSource = products;

推荐阅读