从数据表填充Gridview

时间:2014-02-25 22:54:19

标签: c# gridview datatable

我正在尝试从数据表中填充Gridview。但是,当我运行代码时,Gridview中根本没有显示任何内容。这是代码:

string serverIP = drpServer.SelectedItem.Value.ToString();
ManagementObjectSearcher searcher = new ManagementObjectSearcher(@"\\" + serverIP + "\\root\\CIMV2", "SELECT * FROM Win32_PerfFormattedData_PerfProc_Process");

        foreach (ManagementObject query in searcher.Get())
        {               
            var processName = query["Name"];
            var processID = query["IDProcess"];
            var cpuTime = query["PercentProcessorTime"];
            var memUsage = query["WorkingSet"];

            double newMemUsage = Convert.ToDouble(memUsage);

            newMemUsage = newMemUsage / 1024;

            DataTable dt = new DataTable();
            dt.Columns.Add("ProcessName", typeof(string));
            dt.Columns.Add("ProcessID", typeof(int));
            dt.Columns.Add("CPUTime", typeof(string));
            dt.Columns.Add("MemoryUsage", typeof(string));

            DataRow row = dt.NewRow();
            row["ProcessName"] = processName;
            row["ProcessID"] = processID;
            row["CPUTime"] = cpuTime;
            row["MemoryUsage"] = newMemUsage;
            dt.Rows.Add(row);

            GridView1.DataSource = dt;
            GridView1.DataBind();

我比使用Diagnostics.Process更喜欢管理对象搜索器,这就是我要走那条路的原因。

我也在Gridview中创建了Bound Fields。

1 个答案:

答案 0 :(得分:2)

为什么你的foreach包裹了整个程序?每次获得新查询时,这将创建一个全新的DataTable。我认为您打算执行以下操作,仅包装添加行块:

string serverIP = drpServer.SelectedItem.Value.ToString();
ManagementObjectSearcher searcher = new ManagementObjectSearcher(@"\\" + serverIP + "\\root\\CIMV2", "SELECT * FROM Win32_PerfFormattedData_PerfProc_Process");

DataTable dt = new DataTable();
dt.Columns.Add("ProcessName", typeof(string));
dt.Columns.Add("ProcessID", typeof(int));
dt.Columns.Add("CPUTime", typeof(string));
dt.Columns.Add("MemoryUsage", typeof(string));

foreach (ManagementObject query in searcher.Get())
{   
    var processName = query["Name"];
    var processID = query["IDProcess"];
    var cpuTime = query["PercentProcessorTime"];
    var memUsage = query["WorkingSet"];

    double newMemUsage = Convert.ToDouble(memUsage);

    newMemUsage = newMemUsage / 1024;

    DataRow row = dt.NewRow();
    row["ProcessName"] = processName;
    row["ProcessID"] = processID;
    row["CPUTime"] = cpuTime;
    row["MemoryUsage"] = newMemUsage;
    dt.Rows.Add(row);
}

GridView1.DataSource = dt;
GridView1.DataBind();