简体   繁体   中英

BindingSource.Find with no column name

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;

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));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM