0

I. This is the part of the code in the C# form

this.cbDay.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
            this.cbDay.FormattingEnabled = true;
            this.cbDay.Items.AddRange(new object[] {
            });//items from a loop in another class and method.

II. This is my method in another class

namespace StudentRegistrationApplication
public class loopComboBoxSelection
{
    public loopComboBox(int start, int finsh)
    {
        for (int i = start; i < finsh; i++)
        {
            ComboboxItem item = new ComboboxItem();
            item.Text = "Item " + i;
            item.Value = i;
            ModDown.Items.Add(item);
        }
            
    }
}

III. I want to call the loop method that will generate items from 1 to 100. For this question, what is the syntax?

    this.cbDay.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
                this.cbDay.FormattingEnabled = true;
                this.cbDay.Items.AddRange(new object[] {
                "1"
                "2"
                "3"
                "4"
                "5"});

1 Answers1

0

You're doing it wrong. You should be binding the data to the ComboBox, e.g.

cbDay.DisplayMember = nameof(ComboBoxItem.Text);
cbDay.ValueMember = nameof(ComboBoxItem.Value);
cbDay.DataSource = Enumerable.Range(startValue, endValue - startValue + 1)
                             .Select(i => new ComboBoxItem {Text = $"Item {i}", Value = i})
                             .ToArray();

The Text values will then be displayed in the control and, when the user makes a selection, you can get the corresponding Value from the SelectedValue property of the control.

Note that you don't have to use LINQ to create the list but it's the binding part that's important. By setting the DataSource, you're able to get a specific property value from the SelectedValue rather than just the same as you'd get from SelectedItem.

John
  • 3,057
  • 1
  • 4
  • 10