如何从函数中访问数据以在其他函数中使用?

时间:2018-12-21 14:37:32

标签: c#

我正在为DISM构建GUI,以便在校园中执行成像任务。
我有一个使用WMI的函数来获取驱动器号和索引并将它们放入组合框中。

我的问题是combobox-SelectedIndexChanged。 我希望将字符串var设置为组合框中所选驱动器的索引。

我需要一种方法来引用我的getdrive()

中的对象
private void getdrive()
{

    WqlObjectQuery Query1 = new WqlObjectQuery("SELECT * FROM Win32_DiskDrive");
    ManagementObjectSearcher Search1 = new ManagementObjectSearcher(Query1);
    foreach (ManagementObject Object1 in Search1.Get()) {

        foreach (ManagementObject Object2 in Object1.GetRelated("Win32_DiskPartition")) {

            foreach (ManagementBaseObject Object3 in Object2.GetRelated("Win32_LogicalDisk")) {

                comboBox5.Items.Add(new { Drive = Object1["Index"], Volume = Object3["Name"] }.ToString());
            }
        }
    }
}


private void comboBox5_SelectedIndexChanged(object sender, EventArgs e)
{

    // How do i get the following to work??
    sDISKPARTDRIVE = Object1["Index"];
}

comboxbox结果将显示为:

{ Drive = 1, Volume = D: }

{ Drive = 0, Volume = C: }

{ Drive = 2, Volume = E: }

etc...

1 个答案:

答案 0 :(得分:-1)

为驱动器和卷创建一个类。

    public class DriveClass
    {
        public int Drive { get; set; }
        public string Volume { get; set; }

        public override string ToString()
        {
            return String.Format("{{Drive = {0} Volume = {1}}}", Drive, Volume);
        }
    }

然后您可以将该类添加到组合框中:

comboBox5.Items.Add(new DriveClass { Drive = (int)Object1["Index"], Volume = Object3["Name"] };

然后,您可以在索引更改时检索DriveClass:

    private void comboBox5_SelectedIndexChanged(object sender, EventArgs e)
    {
        DriveClass SelectedDrive = (DriveClass)comboBox5.SelectedItem;
        sDISKPARTDRIVE = SelectedDrive.Drive;
    }