gpt4 book ai didi

c# - 从数据表填充 Gridview

转载 作者:太空宇宙 更新时间:2023-11-03 10:49:32 24 4
gpt4 key购买 nike

我正在尝试从数据表填充 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 相比,我更喜欢 Management Object Searcher,这就是我选择这条路线的原因。

我也在我的 Gridview 中创建了绑定(bind)字段。

最佳答案

为什么您的 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();

关于c# - 从数据表填充 Gridview,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22028006/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com