如何将多个数据绑定到同一个gridview?

时间:2017-11-01 12:33:28

标签: c# asp.net gridview

通过WMI服务循环我从每个服务器获取特定数据。我有一个文本框(serverName.Text),允许您输入多个服务器名称。收集来自第一台服务器的数据后,它会覆盖第二台服务器。如何防止这种情况发生,以便myGridView同时拥有来自每个服务器的数据。感谢

protected void ServerServices()
{
    string txt = serverName.Text;
    string[] servers = txt.Split(new Char[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries);

    ConnectionOptions options = new ConnectionOptions();
    options.Username = "myUserName";
    options.Password = "myPassword";
    options.EnablePrivileges = true;

    foreach (var item in servers)
    {
        //Create the scope that will connect to the default root for WMI
        var scope = new ManagementScope(string.Format(@"\\{0}\root\cimv2", item), options);
        scope.Connect();

        //Create a path to the services with the default options
        ObjectGetOptions option = new ObjectGetOptions(null, TimeSpan.MaxValue, true);
        ManagementPath spoolerPath = new ManagementPath("Win32_Service");
        ManagementClass servicesManager = new ManagementClass(scope, spoolerPath, option);

        DataTable dt = new DataTable();
        ViewState["currentTable"] = dt;
        dt.Columns.Add("Name", typeof(string));
        dt.Columns.Add("DisplayName", typeof(string));
        dt.Columns.Add("Status", typeof(string));

        try
        {
            //Get all of the services running on this server
            using (ManagementObjectCollection services = servicesManager.GetInstances())
            {
                foreach (ManagementObject service in services)
                {
                    if (service["Name"].ToString().StartsWith(include.Text))
                    {
                        if (!service["Name"].ToString().EndsWith(exclude.Text))
                        {
                            if (ViewState["currentTable"] != null)
                            {
                                DataTable currentDt = (DataTable)ViewState["currentTable"];
                                DataRow currentRow = null;
                                currentRow = currentDt.NewRow();

                                currentRow["Name"] = service["Name"].ToString();
                                currentRow["DisplayName"] = service["DisplayName"].ToString();
                                currentRow["Status"] = service["Status"].ToString();

                                currentDt.Rows.Add(currentRow);
                                ViewState["currentTable"] = currentDt;

                                myGridView.DataSource = currentDt;
                                myGridView.DataBind();
                            }
                            else
                            {
                                //Do something
                            }

                        }
                    }
                }
            }

        }
        catch (UnauthorizedAccessException)
        {
            throw;
        }

    }
}

0 个答案:

没有答案