如何从组合框上的选定项中获得值驱动,并与所选项的列表框进行交互

本文关键字:选项 交互 列表 组合 | 更新日期: 2023-09-27 17:49:15

我一直在试图弄清楚到目前为止3个小时,无法得到任何出路,因此我需要帮助。这是我正在尝试的:我希望能够选择驱动器并保持其值,因此,同时我希望它能抛出我试图获得的诸如"空闲空间,类型,可用性等"的详细信息

InitializeComponent();
foreach (var Drives in Environment.GetLogicalDrives())
{
    DriveInfo DriveInf = new DriveInfo(Drives);
    if (DriveInf.IsReady == true)
    {
        comboBox1.Items.Add(DriveInf.Name);
        // to get info for the selected drive
        if (comboBox1.SelectedItem != null)
        {
            comboBox1.SelectedItem = listBox1.Items.Add("Drive Name: " + DriveInf.Name);
            comboBox1.SelectedItem = listBox1.Items.Add("Total Size: " + DriveInf.TotalSize);
            comboBox1.SelectedItem = listBox1.Items.Add("Available Space: " + DriveInf.AvailableFreeSpace);
            comboBox1.SelectedItem = listBox1.Items.Add("Total Free Space: " + DriveInf.TotalFreeSpace);
         }           
     } 
}

如何从组合框上的选定项中获得值驱动,并与所选项的列表框进行交互

所以您希望能够从组合框中选择驱动器,并在从组合框中选择驱动器时填充带有驱动器信息的列表框?

听起来您需要为comboBox1提供一个事件处理程序。SelectionChanged事件。我现在不能访问我的IDE,所以下面的内容还不能完全复制粘贴,但它会让你知道你需要做什么。

下面是我要做的:我要为你的表单创建一个属性
private List<DriveInfo> driveInfoList = new List<DriveInfo>();

然后在你的初始化组件方法之后,我将添加

foreach (var Drives in Environment.GetLogicalDrives())    {
    DriveInfo DriveInf = new DriveInfo(Drives);
    if (DriveInf.IsReady == true)
    {
        driveInfoList.Add(DriveInf);
        comboBox1.Items.Add(DriveInf.Name);
    } 
}

然后我将像这样放置一个事件处理程序,并确保您的comboBox1的SelectionChanged事件连接到它:

private void comboBox1_SelectionChanged(object sender, EventArgs e) //or whatever form the event arguments take.
{
    listBox1.Clear(); //or whatever clears the listbox of current items.
    if (comboBox1.SelectedItem != null)
    {        
        DriveInfo driveInfo = (from DriveInfo d in driveInfoList where d.Name == comboBox1.Text select d).First(); //or whatever you need to do to get the corresponding item from the list.
        listBox1.Items.Add("Drive Name: " + d.Name);
        listBox1.Items.Add("Total Size: " + DriveInf.TotalSize);
        listBox1.Items.Add("Available Space: " + DriveInf.AvailableFreeSpace);
        listBox1.Items.Add("Total Free Space: " + DriveInf.TotalFreeSpace);
     }     

明白了吗?