【发布时间】:2018-05-27 14:31:35
【问题描述】:
我在 Gridview 中有一个 DropDownList,它允许您启动或停止远程服务器上的服务。 DropDownList 将允许您启动或停止服务,但它从列表中的第一个服务开始并循环遍历所有服务。如何让 DropDownList 只对特定行的服务名称而不是整个 Gridview 执行操作?服务被添加到绑定到 GridView 的列表中。谢谢。
protected void ddlAction_SelectedIndexChanged(object sender, EventArgs e)
{
ConnectionOptions options = new ConnectionOptions();
options.Username = "myUsername";
options.Password = "myPassword";
options.EnablePrivileges = true;
serverName.Text = "myServerName";
if (txtbox2.Text != string.Empty)
{
//Create the scope that will connect to the default root for WMI
var scope = new ManagementScope(string.Format(@"\\{0}\root\cimv2", serverName.Text), 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);
try
{
//Get all of the services running on this server
using (ManagementObjectCollection services = servicesManager.GetInstances())
{
foreach (ManagementObject service in services)
{
list.Add(new myServers() { Name = service["Name"].ToString(), State = service["State"].ToString(), Servers1 = serverName.Text });
GridViewRow gvr = ((DropDownList)sender).NamingContainer as GridViewRow;
if (gvr != null)
{
//We can find all the controls in this row and do operations on them
var ddlQuantity = gvr.FindControl("ddlAction") as DropDownList;
if (ddlQuantity != null)
{
if (ddlQuantity.SelectedValue != "-1")
{
if (ddlQuantity.SelectedValue == "1")
{
service.InvokeMethod("StartService", null);
}
else if (ddlQuantity.SelectedValue == "2")
{
service.InvokeMethod("StopService", null);
}
}
}
}
}
}
}
catch (UnauthorizedAccessException)
{
throw;
}
gvServer.DataSource = list;
gvServer.DataBind();
}
}
【问题讨论】:
-
您正在
foreach循环中调用您的方法。你需要知道哪个下拉索引发生了变化(比如一些i),然后只为services[i]调用你的方法 -
谢谢马克。你能提供一个示例代码吗?
-
很难知道你需要什么 foreach 循环和其他方法以及你的观点是什么。但希望答案是有用的。使用
CurrentCell.RowIndex获取当前选中行的索引 -
我将需要 foreach,因为稍后我需要挑选出某些服务。例如 .Contains 或 .Endswith。截至目前,我只是想让下拉菜单按预期运行。
标签: c# asp.net gridview drop-down-menu foreach