Solved

How can I get a value to show in a combobox.dropdownlist?

Posted on 2008-10-11
11
620 Views
Last Modified: 2013-12-17
I have a combobox with DropdownStyle=DropdownList but when I set the SelectedIndex to a value programmatically it does not show up on the combobox. The combobox always shows blank as if nothing was selected until I manually select something from the dropdown list. In which case it shows the value selected.

I have been through the code in debug both before and after the combo box has displayed and the SelectedIndex for the combo box is set correctly - yet it refuses to display the text associated with the selection.

Before the combobox was set to be DropDown and I had no problem getting it to display the initial value.

Is there a way around this? Or, do I have to set some flag to get it to display a programmatically set value?

Thanks,

Steve
0
Comment
Question by:wsprhino
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
11 Comments
 
LVL 63

Expert Comment

by:Fernando Soto
ID: 22696218
Hi wsprhino;

Can you post the code where you change the value of the SelectedIndex and also the code in the file FormName.Designer.cs the section for the comboBox only to see how it is initialized.

I have tried it on my system and when I change the value of the SelectedIndex it changes the text box of the combo box to the value at that index.

Fernando
0
 
LVL 55

Expert Comment

by:Jaime Olivares
ID: 22696434
how did you fill the combobox values? did you use a datasource?
0
 
LVL 14

Expert Comment

by:raja_ind82
ID: 22696600
Create one new project and copy this code in form1.cs. i hope this will work for you

Regards,
M.Raja


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
 
namespace WindowsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            // Put some stuff in the combo box
            comboBox1.Items.Add(new Item("Raja", 1));
            comboBox1.Items.Add(new Item("Red", 2));
            comboBox1.Items.Add(new Item("Muthaiah", 3));
 
        }
 
        private void Form1_Load(object sender, EventArgs e)
        {
            //To select RED
            comboBox1.SelectedIndex  = 1;
        }
 
        // Content item for the combo box
        private class Item
        {
            public string Name;
            public int Value;
            public Item(string name, int value)
            {
                Name = name; Value = value;
            }
            public override string ToString()
            {
                // Generates the text shown in the combo box
                return Name;
            }
        }
 
        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            // Display the Value property
            Item itm = (Item)comboBox1.SelectedItem;            
            MessageBox.Show(itm.Name + itm.Value);
        }
 
        
    }
}

Open in new window

0
Guide to Performance: Optimization & Monitoring

Nowadays, monitoring is a mixture of tools, systems, and codes—making it a very complex process. And with this complexity, comes variables for failure. Get DZone’s new Guide to Performance to learn how to proactively find these variables and solve them before a disruption occurs.

 

Author Comment

by:wsprhino
ID: 22697311

the combobox is a derived class and I can follow its value all the way through my code up to the point where control is returned to the system  I can see this by using a MessageBox I can see that the value is always Narrow once it has been set but gets unset somewhere after I lose control.

If I initialize the combobox in it's constructor to Wide it will display that value - even though it was set to Narrow programmatically.

Attached is the class definition for the LineWidthComboBox and the set/get used to set it's value.

The MessageBox displays Narrow when it runs but when I look at the value in debug, after trapping a change event on another field, it shows as Normal.
[DefaultValue(LineWidth.LineWidthValue.Normal)]
public LineWidth.LineWidthValue FatFatEdgeWidth
{
    get
    {
        return(LineWidth.ParseEdgeWidth(lwcbxFatFatWidth));
    }
    set
    {
//          lwcbxFatFatWidth.SelectedIndex = (int)value;
        lwcbxFatFatWidth.SelectedIndex = 0;
        lwcbxFatFatWidth.Invalidate();
 
        MessageBox.Show(lwcbxFatFatWidth.SelectedItem.ToString());
    }
}
 
###############################
 
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
 
namespace Graphics2D
{
    public class LineWidthComboBox : System.Windows.Forms.ComboBox
    {
        public LineWidthComboBox()
        {
            this.DropDownStyle  = ComboBoxStyle.DropDownList;
 
            this.Size           = new Size(85, 24);
            this.Font           = new Font("Microsoft San Serif",
                                           9.00f,
                                           FontStyle.Regular);
        }
 
        protected override void OnCreateControl()
        {
            base.OnCreateControl();
 
            this.BeginUpdate();
            this.Items.Clear();
            this.Items.Add("Narrow");
            this.Items.Add("Normal");
            this.Items.Add("Wide");
            this.Items.Add("Extra Wide");
            this.EndUpdate();
 
            this.Size           = new Size(85, 24);
            this.Font           = new Font("Microsoft San Serif",
                                           9.00f,
                                           FontStyle.Regular);
 
        }
    }
 
    public class LineWidth
    {
        public enum LineWidthValue
        {
            Narrow      = 0,
            Normal      = 1,
            Wide        = 2,
            [Description("Extra Wide")]
            ExtraWide   = 3
        }
 
        public LineWidth() { }
 
 
        public static LineWidthValue ParseEdgeWidth(LineWidthComboBox cbxWidth)
        {
            LineWidthValue lineWidth;
 
            int selectedIndex = cbxWidth.SelectedIndex;
            try
            {
                lineWidth = (LineWidthValue)LineWidthValue.Parse(typeof(LineWidthValue),
                                                                 cbxWidth.Items[selectedIndex].ToString().Replace(" ", ""));
            }
            catch (ArgumentException)
            {
                lineWidth = LineWidthValue.Normal;
            }
 
            return (lineWidth);
 
        }
        
        public static float GetEdgeWidth(LineWidthValue lineWidth)
        {
            switch (lineWidth)
            {
                case LineWidthValue.Narrow :       return(0.5f);
 
                case LineWidthValue.Normal :       return(1.0f);
 
                case LineWidthValue.Wide :         return(2.0f);
 
                case LineWidthValue.ExtraWide :    return(3.0f);
 
                default :                          return(1.0f);
            }
 
        }
    }
}

Open in new window

0
 
LVL 63

Expert Comment

by:Fernando Soto
ID: 22697674
Hi wsprhino;

I was unable to duplicate your issue. I put together a small application using the control, please try it out and see.

It is possible that something else in the project is causing it. Have you tried cleaning the build files by doing the following?

IDE main menu ->  Build | Clean Solution

The project can be downloaded from here. If it ask for a user name and password it is the same as you use here on the main site.

https://filedb.experts-exchange.com/incoming/ee-stuff/7329-WindowsFormsApplication59.zip

Fernando
0
 

Author Comment

by:wsprhino
ID: 22697796

I was beginning to think that something was changing its value back somewhere else in the project. I have tried to trap everywhere that it could possibly change in debug but I can't see anywhere.

It has to be somewhere between losing control back to the system and the system invoking the draw routine. I will try again putting debugs everywhere and trapping changes.
0
 

Author Comment

by:wsprhino
ID: 22699502

I have reduced the problem I am having to a form which includes a panel which contains a simple derived combo box. The combo box is initialized in Program.cs and the panel receives the value. But the value never displays on the combo box.

If I change the combobox type in the LineWidthComboBox() constructor to DropDown, instead of DropDownList, the initial value is displayed on the form. But I cannot get the project to work when the DropDownStyle is DropDownList.

Am I doing something wrong? Is it just my machine?

If anyone is interested in figuring out what the problem is I would be very grateful. I have tried attaching the project directory with the .exe files deleted but the uploader will not allow me to do the upload. If someone would let me know how I can upload the project it would be good.

The uploader doesn't allow .resx and other basic project files as far as I can see,

Thanks,
Steve

Thanks,
Steve
0
 

Author Comment

by:wsprhino
ID: 22699622

I have uploaded the project that I created for this problem to ExpertsExchangeStuff it is at this link :

https://filedb.experts-exchange.com/incoming/ee-stuff/7330-BugTest.zip

Thanks again to anyone who wants to look at it,

Steve
0
 
LVL 63

Accepted Solution

by:
Fernando Soto earned 500 total points
ID: 22700145
Hi wsprhino;

In the class TileRhombEdgesPanel you set up the comboBox at design time with these values:

//
// lwcbxThinThinWidth
//
this.lwcbxThinThinWidth.BackColor = System.Drawing.SystemColors.Window;
this.lwcbxThinThinWidth.DropDownWidth = 70;
this.lwcbxThinThinWidth.Font = new System.Drawing.Font("Microsoft Sans Serif", 9F);
this.lwcbxThinThinWidth.FormattingEnabled = true;
this.lwcbxThinThinWidth.Items.AddRange(new object[] {
"Narrow",
"Normal",
"Wide",
"Extra Wide"});
this.lwcbxThinThinWidth.Location = new System.Drawing.Point(62, 19);
this.lwcbxThinThinWidth.Name = "lwcbxThinThinWidth";
this.lwcbxThinThinWidth.Size = new System.Drawing.Size(85, 23);
this.lwcbxThinThinWidth.TabIndex = 334;

Then just before the form is displayed to the user the system calls the class LineWidthComboBox OnCreateControl which does the following:

base.OnCreateControl();

this.BeginUpdate();
this.Items.Clear();
this.Items.Add("Narrow");
this.Items.Add("Normal");
this.Items.Add("Wide");
this.Items.Add("Extra Wide");
this.EndUpdate();

this.Size  = new Size(85, 24);
this.Font  = new Font("Microsoft San Serif", 9.00f, FontStyle.Regular);

The first thing you do after the BeginUpdate call is to clear all the values from the dropdown list and then re-populate the drop down values then re-sets the SelectedIndex to -1, no selection. If you comment out the code from the BeginUpdate to the EndUpdate then the combo box will display correctly.

Another thing in this same code is that the InitializeComponent never gets called because there is no call to it in the constructor.

In the code file Program.cs you have this:

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            TileRhombEdgesForm tref = new TileRhombEdgesForm();
            tref.ThinThinEdgeWidth = LineWidth.LineWidthValue.Wide;

            Application.Run(tref);

Anything you do to the TileRhombEdgesForm class before the call to Application.Run that will cause an event to be triggered will not occurr because the Application.Run is where the windows message loop gets started. Any changes to the class should be done in the constructor.

Fernando
0
 

Author Closing Comment

by:wsprhino
ID: 31505382
That's really great it had been driving me nuts for a couple of days. At least, I understand what is going on a lot better now.

Thanks very much,

Steve
0
 
LVL 63

Expert Comment

by:Fernando Soto
ID: 22701744
Not a problem Steve, glad I was able to help.  ;=)
0

Featured Post

Free Tool: Subnet Calculator

The subnet calculator helps you design networks by taking an IP address and network mask and returning information such as network, broadcast address, and host range.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

The object model of .Net can be overwhelming at times – so overwhelming that quite trivial tasks often take hours of research. In this case, the task at hand was to populate the datagrid from SQL Server database in Visual Studio 2008 Windows applica…
Real-time is more about the business, not the technology. In day-to-day life, to make real-time decisions like buying or investing, business needs the latest information(e.g. Gold Rate/Stock Rate). Unlike traditional days, you need not wait for a fe…
The Email Laundry PDF encryption service allows companies to send confidential encrypted  emails to anybody. The PDF document can also contain attachments that are embedded in the encrypted PDF. The password is randomly generated by The Email Laundr…
Finds all prime numbers in a range requested and places them in a public primes() array. I've demostrated a template size of 30 (2 * 3 * 5) but larger templates can be built such 210  (2 * 3 * 5 * 7) or 2310  (2 * 3 * 5 * 7 * 11). The larger templa…

734 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question