Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/wix/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# c当字符串中有值名称时,如何选择列表框项?_C#_Listbox - Fatal编程技术网

C# c当字符串中有值名称时,如何选择列表框项?

C# c当字符串中有值名称时,如何选择列表框项?,c#,listbox,C#,Listbox,我有一个字符串“item3”和一个带有“item1、item2、item3、item4”的列表框,当我有一个字符串中的项目名称时,如何在列表框中选择item3 谢谢是否未选择读取/写入值 listBox.FindStringExact("item3"); 返回找到的第一个项的索引,如果找不到匹配项,则返回ListBox.NoMatches 然后你可以打电话 listBox.SetSelected(index, true); 要选择此项,请尝试使用方法。可能如下所示: public bool

我有一个字符串“item3”和一个带有“item1、item2、item3、item4”的列表框,当我有一个字符串中的项目名称时,如何在列表框中选择item3


谢谢

是否未选择读取/写入值

listBox.FindStringExact("item3");
返回找到的第一个项的索引,如果找不到匹配项,则返回ListBox.NoMatches

然后你可以打电话

listBox.SetSelected(index, true);
要选择此项,请尝试使用方法。

可能如下所示:

public bool SelectItem(ListBox listBox, string item)
    {
        bool contains = listBox.Items.Contains(item);
        if (!contains)
            return false;
        listBox.SelectedItem = item;
        return listBox.SelectedItems.Contains(item);
    }
试验方法:

public void Test()
    {
        string item = "item1";
        if (!SelectItem(listBox, item))
        {
            MessageBox.Show("Item not found.");
        }
    }

只有为列表框设置了ValueMember,SelectedValue才会起作用

此外,即使您确实设置了ValueMember,如果您的ListBox.Sorted=true,selectedValue也将不起作用

查看我在上的帖子

您可以尝试以下方法之一:

lb.SelectedValue=字段值

lb.SelectedIndex=lb.FindStringExactfieldValue

这是所有列表框的通用方法。您的实现将根据您绑定到列表框的内容进行更改。在我的例子中,它是DataTable

private void SetSelectedIndex(ListBox lb, string value)
{
    for (int i = 0; i < lb.Items.Count; i++)
    {
        DataRowView dr = lb.Items[i] as DataRowView;
        if (dr["colName"].ToString() == value)
        {
            lb.SelectedIndices.Add(i);
            break;
        }
    }    
}

我试过lstbox.selectedvalue=strItem;但这似乎对我不起作用。这是WinForms还是WebForms?如果selectedValue不起作用,你能发布你的代码吗?你在使用WPF吗?我知道在一些控件中,SelectedValue不是R/W。如果是这样,请记住将WPF问题标记为WPF。如果没有,就别理我;更好的消息是找不到项。或者您可以执行lb.SelectedIndex=lb.FindStringExactfieldValue;这些都不适合我,因为我没有.SetSelected函数。。。我刚刚发现我使用的是System.Controls中的ListBox,这是不同的。这是我第一次在SO中看到一个女孩。很高兴见到你。但无论如何,我的研究所都在敦促我指出一些错误,但毫无用处。你的回答完全正确,我查过了。
private void SetSelectedIndex(ListBox lb, string value)
{
    for (int i = 0; i < lb.Items.Count; i++)
    {
        DataRowView dr = lb.Items[i] as DataRowView;
        if (dr["colName"].ToString() == value)
        {
            lb.SelectedIndices.Add(i);
            break;
        }
    }    
}
static class ControlHelper
{
    public static void SelectExactMatch(this ComboBox c, string find)
    {
        c.SelectedIndex = c.FindStringExact(find, 0);
    }
}
CheckBoxList.Items.FindByValue("Value").Selected = true;