FindFtem或在WPF中查找Listview中的字符串/记录

时间:2012-09-22 03:27:56

标签: c# wpf listview

我一整天都在搜索WPF中listview中的记录/项目/字符串,但没有运气。我刚刚开始WPF专门用于#。在我的程序中,我有textbox / textblock按钮和listview ....假设我已经在listview中有记录。顺便说一句,在listview中我有参考代码列和详细信息。例如,当我在文本框中输入“12345”并单击“搜索”按钮时,如果记录不存在但是记录在列表视图中,它将给我一条消息。它会Selected=True;

这是我在VB.net中的代码(不是WPF),我想在WPF C#中这样做

For ist As Integer = 0 To LVNewBill.Items.Count - 1
    LVNewBill.Items(ist).Selected = False
Next

For i As Integer = 0 To LVNewBill.Items.Count - 1
    'If LVNewBill.Items(i).SubItems(0).Text.Contains(str) Then
    If LVNewBill.Items(i).Text.Contains(InsertChange) Then
        LVNewBill.Items(i).Selected = True
        LVNewBill.Items(i).EnsureVisible()

        'If the Record Found it will Update

        With Me.LVNewBill.SelectedItems(0).SubItems
            '.Item(0).Text = txtrefcode.Text
            .Item(1).Text = txtdetails.Text
            .Item(2).Text = txtperiod.Text
            .Item(3).Text = txtduedate.Text
            Dim newtxtamt As Double = txtamt.Text
            .Item(4).Text = newtxtamt.ToString("###,###,##0.#0")
        End With
    Else
        ' add to lvmain
    End If
Next

2 个答案:

答案 0 :(得分:0)

主要方法:

    private void init()
    {
        listView1.Items.Add(new ListViewItem() { Content = "Hi" });
        listView1.Items.Add(new ListViewItem() { Content = "Hello"});
        listView1.Items.Add(new ListViewItem() { Content = "Buy" });
    }

    private bool find(string str)
    {
        foreach (ListViewItem item in listView1.Items)
        {
            if (item.Content.Equals(str))
            {
                return true;
            }
        }

        return false;
    }

    private void select(string str)
    {
        foreach (ListViewItem item in listView1.Items)
        {
            if (item.Content.Equals(str))
            {
                item.IsSelected = true;
            }
            else
            {
                item.IsSelected = false;
            }
        }
    }

    private void onSelectedClickHandler(object sender, RoutedEventArgs e)
    {
        if (find(searchTextBox.Text))
        {
            select(searchTextBox.Text);
        }
        else
        {
            MessageBox.Show("Not found");
        }
    }

答案 1 :(得分:0)

我会在这里使用linq查询。

var qry = from t in LVNewBill.Items
          where t.Text.Contains(InsertChange) 
          select t;

foreach(var item in qry)
{
      item.Selected = true;
      item.EnsureVisible();
      item.SubItems[1].Text = txtdetails.Text;
      item.SubItems[2].Text = txtperiod.Text;
      item.SubItems[3].Text = txtduedate.Text;

      //Might want to consider TryParse here
      double newtxtamt  = double.Parse(txtamt.Text); 
      item.SubItems[4].Text = newtxtamt.ToString("###,###,##0.#0");
}