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 | Visual Studio | Other
A family of Microsoft suites of integrated development tools for building applications for Windows, the web, mobile devices and many other platforms. Miscellaneous topics that do not fit into specific categories.
Developer technologies | C#
Developer technologies | C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
{count} votes

1 answer

Sort by: Most helpful
  1. Karen Payne MVP 35,591 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' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.