简体   繁体   中英

How to Add and read Index to WinForm ComboBox

I am working on .NET 4.0 WinForm Application. I need comboBox that I need to add with range & IndexId followed by when I choose value from dropdown then capture Id for processing instead of the string value.

I have list that I like to add in range

List

 var distinctPermissions = permissions.GroupBy(_ => _.LevelCategoryName).Select(_ => _.First()).Select(_ => new { _.UserLevelCategoryId, _.LevelCategoryName }).ToList();

I can just show string value by doing following code;

 var distinctPermissions = permissions.GroupBy(_ => _.LevelCategoryName).Select(_ => _.First()).Select(_ => _.LevelCategoryName ).ToList();

 var distinctPermissionNamesList = distinctPermissions.ToArray<string>();

 SystemAComboBox.Items.AddRange(distinctPermissionNamesList);

That is how I am reading drop down string value that I need to pick index instead of string

var systemAComboBox = SystemAComboBox.SelectedItem;

在此处输入图像描述

ComboBox

SystemAComboBox.Items.AddRange(distinctPermissionNamesList);

you can write this

    class ComboBoxItem
    {
        public int Id {get;set;}
        public string Name {get;set;}
        public override string ToString()=>Name;
      
    }
    var distinctPermissions = permissions.GroupBy(_ => _.LevelCategoryName).Select(_ => _.First()).Select(_ => new ComboBoxItem{ Id = _.UserLevelCategoryId,Name= _.LevelCategoryName }).ToList();
    foreach(var item in distinctPermissions){
        SystemAComboBox.Items.Add(item);
    }

when you select a item

ComboBoxItem item = SystemAComboBox.SelectedItem as SystemAComboBox;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM