How to use LINQ to select data from combobox with where filter

T.Zacks 3,996 Reputation points
2021-05-01T12:53:25.07+00:00

I am working with winform. I found this code which throwing error The type or namespace name 'ComboBoxItem' could not be found (are you missing a using directive or an assembly reference?)

var selectedperiods = cboPeriods.Items.Cast<ComboBoxItem>().Where(i => (int.Parse(i.Value.ToString())) == 1);

i am getting error for ComboBoxItem. tell me how to sort it ?. i have to use LINQ to extract data from ComboBox with where filter. thanks

Developer technologies C#
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Ken Tucker 5,861 Reputation points
    2021-05-01T17:30:20.767+00:00

    Assuming this is for a windows forms combobox. You could try casting it to the object type in the combobox. I assume you added integers like this to the combobox.

            comboBox1.Items.Add(1);
            comboBox1.Items.Add(2);
            comboBox1.Items.Add(3);
            comboBox1.Items.Add(4);
            comboBox1.Items.Add(5);
            comboBox1.Items.Add(6);
            comboBox1.Items.Add(7);
            comboBox1.Items.Add(8);
            this.Load += Form1_Load;
        }
    
        private void Form1_Load(object sender, EventArgs e)
        {
            var itm = comboBox1.Items.Cast<int>().Where(i => i == 1);
        }
    
    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.