Winforms ComboBox Modify Display Text

bryon 101 Reputation points
2023-02-17T18:49:23.1733333+00:00

Hello All

I am working on a winforms application, and am trying to find a way to modify the displayed text when the collection is bound to the control.

           foreach (var time in timeTable)
            {
                comboBox.Items.Add(time);
            }

            comboBox.DataSource = timeTable;
            comboBox.DisplayMember = nameof(TimeTable.DisplayText);
            comboBox.ValueMember = nameof(TimeTable.TimeSpan);

As of now the combobox looks like this: (2hr)

I want to look like this "TimeFrame: (2hr)"

How would I modify this? I was looking at using ownerdraw, but I am not sure how to go about that route.

I cannot modify the class that this is dependant on as the properties are readonly. I have no control over this.

Developer technologies | Visual Studio | Other
Developer technologies | C#
{count} votes

1 answer

Sort by: Most helpful
  1. Karen Payne MVP 35,586 Reputation points Volunteer Moderator
    2023-02-17T19:09:15.5533333+00:00

    You need to create your own class as shown below (Id is optional), keep in mind this is a proof of concept.

    2023-02-17_11-08-39

    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            comboBox1.DataSource = new List<TimeItem>
            {
                new () { Id = 1, Time = new TimeSpan(12, 0, 0) },
                new () { Id = 2, Time = new TimeSpan(10, 0, 0) },
                new () { Id = 3, Time = new TimeSpan(8,0,0)}
            };
        }
    
        private void GetButton_Click(object sender, EventArgs e)
        {
            var current = comboBox1.SelectedItem as TimeItem;
            MessageBox.Show(current!.Id.ToString());
        }
    }
    
    public class TimeItem
    {
        public int Id { get; set; }
        public TimeSpan Time { get; set; }
        public override string ToString() => $"TimeFrame ({Time:hh})";
    
    }
    
    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.