如何获取每个项目的ComboBox项目文本?

时间:2015-04-19 20:37:08

标签: c# .net winforms

在我做的构造函数中:

ComboboxItem item1 = new ComboboxItem();
item1.Text = "Processor";
item1.Value = "Win32_Processor";
ComboboxItem item2 = new ComboboxItem();
item2.Text = "DiskDrive";
item2.Value = "Win32_DiskDrive";
cmbxOption.Items.Add(item1);
cmbxOption.Items.Add(item2);

ComboboxItem[] items = new ComboboxItem[cmbxOption.Items.Count];

for (int i = 0; i < items.Length; i++)
{
    items[i] = new ComboboxItem();
    items[i].Text = cmbxOption.GetItemText(i);
}

但是,为每个项目执行一个新实例并将项目添加到cmbxOption我想创建一个for循环,将cmbxOption中的所有项添加到ComboboxItem[]

在属性项的ComboBox中的form1设计器中,我已经拥有了Collection中的项目:

Win32_1394Controller
Win32_1394ControllerDevice
Win32_BaseBoard
Win32_Battery
Win32_BIOS
Win32_Bus
Win32_CDROMDrive
Win32_CIMLogicalDeviceCIMDataFile
Win32_DeviceBus
Win32_DeviceMemoryAddress
Win32_DeviceSettings
Win32_DisplayConfiguration
Win32_DisplayControllerConfiguration
Win32_DMAChannel
Win32_DriverVXD
Win32_FloppyController
Win32_FloppyDrive
Win32_HeatPipe
Win32_IDEController
Win32_IDEControllerDevice
Win32_InfraredDevice
Win32_IRQResource
Win32_Keyboard
Win32_MotherboardDevice
Win32_OnBoardDevice
Win32_PCMCIAController
Win32_PNPAllocatedResource
Win32_PnPDevice
Win32_PnPEntity
Win32_PointingDevice
Win32_PortableBattery
Win32_PortConnector
Win32_PortResource
Win32_POTSModem
Win32_POTSModemToSerialPort
Win32_PowerManagementEvent
Win32_Printer
Win32_PrinterConfiguration
Win32_PrinterController
Win32_PrinterDriverDll
Win32_PrinterSetting
Win32_PrinterShare
Win32_PrintJob
Win32_Processor
Win32_SCSIController
Win32_SCSIControllerDevice
Win32_SerialPort
Win32_SerialPortConfiguration
Win32_SerialPortSetting
Win32_SMBIOSMemory
Win32_SoundDevice
Win32_TemperatureProbe
Win32_USBController
Win32_USBControllerDevice
Win32_VideoConfiguration
Win32_VideoController
Win32_VideoSettings
Win32_VoltageProbe

我想采取每个项目并为其创建ComboboxItem文本和值。只是不要手动。

这是我做过的课程:

public class ComboboxItem
        {
            public string Text { get; set; }
            public object Value { get; set; }

            public override string ToString()
            {
                return Text;
            }
        }

然后这是我在选择项目时使用它的方式:

private void cmbxOption_SelectedIndexChanged(object sender, EventArgs e)
        {
            InsertInfo((cmbxOption.SelectedItem as ComboboxItem).Value.ToString(), ref lstDisplayHardware, chkHardware.Checked);
        }

当我在构造函数中手动执行时,它会在每次向cmbxOption文本和值添加新项目时添加,但是添加每个项目手册我想使用我在cmbxOption中已有的项目。

1 个答案:

答案 0 :(得分:0)

GetItemText只返回对象的文本表示,而不是索引上项目的文本。试试这个:

using System.Linq;

ComboboxItem[] items = cmbxOption.Items.Cast<string>().Select(s => new ComboboxItem{Value = s, Text = s.Substring(6)}).ToArray();