Home > Software design >  Unable to format items in a ToolStripComboBox control
Unable to format items in a ToolStripComboBox control

Time:01-08

Has anyone figured out how to format items in a ToolStripComboBox?

This control has no FormatString property, but it does have a ComboBox property, which provides full access to the underlying ComboBox control.

But setting that FormatString has absolutely no effect.

tsComboBox.ComboBox.FormatString = "MMMM, yyyy";

I have no control over the formatting of items. Does anyone know how to work around this?

CodePudding user response:

You could do the typical "bind a two property thing, setting one prop to be the formatted display item and the other to be the value" route:

var dt = new DataTable();
dt.Columns.Add("Disp");
dt.Columns.Add("Val", typeof(int));
dt.Rows.Add("Hello", 1);
dt.Rows.Add("Goodbye", 2);


toolStripComboBox1.ComboBox.DisplayMember = "Disp";
toolStripComboBox1.ComboBox.ValueMember = "Val";
toolStripComboBox1.ComboBox.DataSource = dt;

Then pull it with SelectedValue:

MessageBox.Show($"value is {toolStripComboBox1.ComboBox.SelectedValue} an {toolStripComboBox1.ComboBox.SelectedValue.GetType()}"); 

Doesn't have to be a datatable; DataSource could be e.g. a List<KeyValuePair>, a List<YourClass> etc


If you're looking for something more minimal you can provide something that overrides ToString:

    toolStripComboBox1.ComboBox.DataSource = 
            Enumerable.Range(1, 12)
            .Select(i => new MyX { X = DateTime.Now.AddDays(i * 30) })
            .ToList();




    class MyX
    {
        public DateTime X { get; set; }
        public override string ToString() 
            => X.ToString("MMMM, yyyy"); 
    }

enter image description here

  •  Tags:  
  • Related