我在Winforms ComboBox中有这样的条目:
Font 8 pt
Font 9 pt
Font 10 pt
Font 12 pt
Font 14 pt
然后我有搜索字符串" 9"。
这是本地方式通过搜索字符串查找索引而不循环?
我试试这个:
Dim a As Integer = myComboBox.FindString(" 9 ", 0)
......但没有好结果。
答案 0 :(得分:2)
首先,不,框架中没有可用的方法来搜索组合框项目中的子字符串,并返回包含搜索参数的第一个项目的索引。
但即使ComboBox.FindString
使用循环,您也可以看到in the source。
所以使用一个没有什么不好,你可以为此编写一个扩展方法:
public static class ControlExtensions
{
public static int FindSubStringIndex(this ComboBox combo, string subString, StringComparison comparer = StringComparison.CurrentCulture)
{
// Sanity check parameters
if(combo == null) throw new ArgumentNullException("combo");
if (subString == null) {
return -1;
}
for (int index = 0; index < combo.Items.Count; index++)
{
object obj = combo.Items[index];
if(obj == null) continue;
string item = Convert.ToString(obj, CultureInfo.CurrentCulture);
if (string.IsNullOrWhiteSpace(item) && string.IsNullOrWhiteSpace(subString))
return index;
int indexInItem = item.IndexOf(subString, comparer);
if (indexInItem >= 0)
return index;
}
return -1;
}
}
现在您可以这样使用它:
int index = combo.FindSubStringIndex("9");
哎呀,VB.NET:
Public Module ControlExtensions
<System.Runtime.CompilerServices.Extension> _
Public Function FindSubStringIndex(combo As ComboBox, subString As String, Optional comparer As StringComparison = StringComparison.CurrentCulture) As Integer
' Sanity check parameters
If combo Is Nothing Then
Throw New ArgumentNullException("combo")
End If
If subString Is Nothing Then
Return -1
End If
For index As Integer = 0 To combo.Items.Count - 1
Dim obj As Object = combo.Items(index)
If obj Is Nothing Then
Continue For
End If
Dim item As String = Convert.ToString(obj, CultureInfo.CurrentCulture)
If String.IsNullOrWhiteSpace(item) AndAlso String.IsNullOrWhiteSpace(subString) Then
Return index
End If
Dim indexInItem As Integer = item.IndexOf(subString, comparer)
If indexInItem >= 0 Then
Return index
End If
Next
Return -1
End Function
End Module