0

I have a C#.net winforms application which uses Entity Framework code first to connect to SQL DB.

One of my combo boxes loses the list of values that its supposed to pull from an enumeration (list of the 12 months) and it just shows the name of the month list object.

It happened since I changed code which is completely unrelated to the combo and should not affect it (moved some unrelated code to another class) and it seems to have caused the issue above. Something similar happened previously when I added some new code it caused the same thing to happen. Eventually it fixed itself after i changed a linq query to return a "TBC" string when a certain value was null. Bearing in mind the code changed has nothing to do with the combo box in question. The combo is also populated before any of the unrelated code ever runs.

This is the code that populates the combo:

private void UpdateMonthCombo()
{
    ArrayList AL = new ArrayList();
    foreach (string cs in Enum.GetNames(typeof(MonthsEnum)))
    {
        MonthList aEnum = new MonthList((int) Enum.Parse(typeof(MonthsEnum), cs), cs);
        AL.Add(aEnum);
    }

    BindingSource source = new BindingSource();
    source.DataSource = AL;
    comboMonth.ValueMember = "_MonthNumber";
    comboMonth.DisplayMember = "_Name";
    comboMonth.DataSource = source;
    comboMonth.SelectedItem = null;
}

I'd love to know how this can happen and how to fix and prevent it. I'm sure you can tell that i'm relatively new to C#!

Any help is much appreciated.

This is MonthList class:

public class MonthList
{

    public string _Name { get; set; }
    public int _MonthNumber { get; set; }

    public MonthList(int MonthNumber, string Name)
    {
        _Name = Name;
        _MonthNumber = MonthNumber;
    }
    public enum MonthsEnum : int
    {
        January = 1,
        February = 2,
        March = 3,
        April = 4,
        May = 5,
        June = 6,
        July = 7,
        August = 8,
        September = 9,
        October = 10,
        November = 11,
        December = 12
    }       
}

Tried using this instead of the enumeration. Tested on separate form works as expected. But on my form it only displays the month numbers:

private void UpdateMonthCombo()
    {
        var monthList = CultureInfo.InvariantCulture.DateTimeFormat.MonthNames.Select((item, index) => new
        {
            Month = item,
            Value = index + 1
        });

        var result = monthList.Where(m => m.Month != "");

        comboMonth.DataSource = result.ToList();
        comboMonth.ValueMember = "Value";
        comboMonth.DisplayMember = "Month";
    }

I refactored my selectedindexchanged event on the combo box. It fixed the combobox. But now the main gridview is broken. It seems related to a method which adds a combobox column. When i comment out this method the gridview shows all columns (no combo column) but the original comboMonth becomes broken again showing just the month numbers:

private void AddProjectCombo()
    {
        gridBusinessKMs.Columns["Project"].Visible = false;
        DataGridViewComboBoxColumn cmbCol = new DataGridViewComboBoxColumn();

        cmbCol.DisplayStyle = DataGridViewComboBoxDisplayStyle.Nothing;
        cmbCol.HeaderText = "Project";
        cmbCol.Name = "Project ";
        cmbCol.Items.Add("True");

        using (var context = new MileageLogDBContext())
        {
            cmbCol.DataSource = (from p in context.Projects
                                 orderby p.ProjectDescription
                                 select p.ProjectDescription).ToList();
        }
        gridBusinessKMs.Columns.Add(cmbCol);
        gridBusinessKMs.Columns["Project "].DisplayIndex = 1;
    }
Salbrox
  • 143
  • 1
  • 15
  • 1
    can you add some code which we can check, looks like class objects are being bind with combo instead of property/member of class – Mukesh Chudasama Jul 18 '17 at 15:06
  • Some specific code would be helpful to see what happened. – Thomas Jager Jul 18 '17 at 15:06
  • comboMonth.DataSource = source; is this not the name of the data source object? – Bender Bending Jul 18 '17 at 15:09
  • I hasve changed to comboMonth.DataSource = AL; but issue remains. – Salbrox Jul 18 '17 at 15:15
  • I tried this: `private void UpdateMonthCombo() { var monthList = CultureInfo.InvariantCulture.DateTimeFormat.MonthNames.Select((item, index) => new { Month = item, Value = index + 1 }); var result = monthList.Where(m => m.Month != ""); comboMonth.DataSource = result.ToList(); comboMonth.ValueMember = "Value"; comboMonth.DisplayMember = "Month"; }` ...it works on a separate form but when added to my original form it only displays numbers in the combo – Salbrox Jul 19 '17 at 10:19

1 Answers1

0

I believe that ArrayList holds references to objects and you could possibly be changing the object and thus the binding source. (see the answer to this question: ArrayList vs List<> in C#) If the binding source was changed then the value of DisplayMember may revert to the object's ToString method:

If the specified property does not exist on the object or the value of DisplayMember is an empty string (""), the results of the object's ToString method are displayed instead.

https://msdn.microsoft.com/en-us/library/system.windows.forms.listcontrol.displaymember(v=vs.110).aspx

I don't know what MonthsEnum or MonthList are doing but I tested the following code and it worked.

private void UpdateMonthCombo()
    {
        List<Tuple<int, string>> AL = new List<Tuple<int, string>>();

        string[] monthNames = System.Globalization.CultureInfo.CurrentCulture.DateTimeFormat.MonthNames;

        for (int i = 0; i < 12; i++)
        {
            AL.Add(new Tuple<int, string>(i + 1, monthNames[i]));
        }

        comboMonth.DataSource = AL;
        comboMonth.ValueMember = "Item1";
        comboMonth.DisplayMember = "Item2";
        comboMonth.SelectedItem = null;
    }
  • That caused some errors (along the lines of "Only primitive types or enumeration types are supported in this context.") with LINQ queries I use to populate some grids. I modified them and the form opened but comboMonth just showed numbers from 1 to 12 instead of the month names. – Salbrox Jul 19 '17 at 09:40
  • @Salbrox it would seem that if you have code that is working in another form that the bug remains in your original form not in the code that you have working. I suspect that you have code that is modifying some portion of the combobox and the displaymember is reverting to ToString() method. (If you comment out the line `comboMonth.DisplayMember = "Item2";` then the combobox reverts to just the numbers of the month.) –  Jul 19 '17 at 15:34
  • I seem to have fixed the combobox by refactoring the SelectedIndexChanged event of the combo box. I do not know why or how that can affect the combo's DisplayMember but it does. But now my gridview is broken! It only shows one column. I have a metho which adds a column with a combobox. When I comment it out the gridview shows all columns but the original combobox goes back to numbers only! Very confused by all of this now. – Salbrox Jul 19 '17 at 16:40
  • @Salbrox Sounds like a mystery. If you want to post additional code snippets I'd be interested in looking for the bug. –  Jul 19 '17 at 16:59
  • I managed to fix it. I dont understand why though. I had a method which pulled the currently selected month and passed it as a parameter to another method which returns a value. The method was looking for a value from a global variable but was also set up to accept the same value as a parameter. I changed the code so that it took the parameter and it worked. I don't understand how this can affect the displaymember of the combo box supplying the parameter. Anyway its working ok now. – Salbrox Jul 20 '17 at 15:38
  • @Salbrox I couldn't reproduce the error but I think you were passing something in by reference and by editing that value you editing the same value in memory. This is the best article on parameters in C#: http://jonskeet.uk/csharp/parameters.html –  Jul 20 '17 at 16:00
  • Thanks Adam i'll have a look at that. Right now i'm just happy to have the issue fixed even if i haven't yet figured out why. Has been frying my head for a few days now! – Salbrox Jul 21 '17 at 10:56
  • @Salbrox no problem. Good luck. –  Jul 21 '17 at 16:03