Reputation: 458
I've got a BindingSource as DataSource for a ComboBox. The BindingSource's source data is a List<String>
which obviously doesn't have column names, but only a list of strings. The BindingSource.Find method expects a column name to search on, so I cannot simply use this function. I need to set the ComboBox to a specific selected item and since the source data is a BindingSource, I think it would be best to work with the BindingSource to achieve my goal.
How can I set the correct item in the BindingSource by finding on a specific string value?
Code example:
readonly List<String> _metaList = new List<String>();
...
while (reader.Read())
{
_metaList.Add(reader.GetString(0));
}
comboBoxPartities.DataSource = new BindingSource(_metaList, null);
comboBoxPartities.DisplayMember = "Key";
And later on, I need to achieve something like this:
var bs = (BindingSource) comboBoxPartities.DataSource;
var i = bs.Find("?!!", lastProcessedTable);
((BindingSource) comboBoxPartities.DataSource).Position = i;
Upvotes: 0
Views: 796
Reputation: 460158
You could use List.IndexOf
and BindingSource.Position
:
List<string> metaList = (List<string>) bs.DataSource;
int position = metaList.IndexOf("foo");
bs.Position = position;
If that string was not found in the list, the first item will be the current item.
Another method that you can use is List.FindIndex
which allows to search case-insensitive:
int position = metaList.FindIndex(s => string.Equals(s, "Foo", StringComparison.CurrentCultureIgnoreCase));
Upvotes: 1