changing combobox text

D

Dan

I'd like to change the text inserted in the text portion of a combobox
control whenever the user selects an item from its list: let's say the items
list contains some explanatory text followed by the value to be inserted,
e.g.:

one [1]
two [2]
three [3]

the user can type a value (e.g. "2") or select it from the list: in this
case, I do not want to store "two [2]" but just "2" in the text box. I tried
to do this with the following handler (let's say the combobox is named
_cboTest):

private void _cboTest_SelectionChangeCommitted(object sender,
System.EventArgs e)
{
string s = (string)_cboTest.SelectedItem;
int x = s.LastIndexOf('[');
if (x > -1) _cboTest.Text = s.Substring(x+1, s.Length - 2 - x);
}

the code itself works, but as soon as the text is programmatically set (e.g.
to "2") it is reverted by the framework to the selected item's text (e.g. to
"two [2]"). How can I avoid this?

Thanx guys!
 
M

Morten Wennevik

Hi Dan,

I think you may need to OwnerDraw the ComboBox.

Keep a list of values that will be displayed in the edit box, and another
that will be displayed in the dropdownlist.

Fill the combobox with the first set of strings.

Set the ComboBox DrawMode = OwnerDrawFixed

Then use something like this in the DrawItem event (formattet for this
message)

private void cb_DrawItem(object sender,
System.Windows.Forms.DrawItemEventArgs e)
{
Graphics g = e.Graphics;
for(int i = 0; i < cb.Items.Count; i++)
{
if(cb.SelectedIndex == i) // mark selected text
{
g.FillRectangle
(
SystemBrushes.Highlight,
0,
cb.ItemHeight*i,
cb.DropDownWidth,
cb.ItemHeight
);
g.DrawString
(
dropdowntext,
cb.Font,
SystemBrushes.HighlightText,
0,
cb.ItemHeight*i
);
}
else
{
g.FillRectangle
(
SystemBrushes.Window,
0,
cb.ItemHeight*i,
cb.DropDownWidth,
cb.ItemHeight
);
g.DrawString
(
dropdowntext,
cb.Font,
SystemBrushes.ControlText,
0,
cb.ItemHeight*i
);
}
}
g.Dispose();
}


Happy coding!
Morten Wennevik [C# MVP]
 
D

Dan

Nice idea... Thanks Morten!

Hi Dan,

I think you may need to OwnerDraw the ComboBox...
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top