-1

データベースからリストビューまでのすべてのレコードを表示するためにこれがあります

   private void populatelistview()
    {
        listView1.Items.Clear();
        using (SqlConnection myDatabaseConnection = new SqlConnection(myConnectionString.ConnectionString))
        {
            myDatabaseConnection.Open();
            using (SqlCommand SqlCommand = new SqlCommand("Select * from Employee", myDatabaseConnection))
            {
                SqlCommand.CommandType = CommandType.Text;
                SqlDataReader dr = SqlCommand.ExecuteReader();
                while (dr.Read())
                {
                    listView1.Items.Add(new ListViewItem(new string[] { dr["EmpID"].ToString(), dr["Lname"].ToString(), dr["Fname"].ToString() }));
                }
            }
        }
    }

たとえば、次の結果があります。

EmpID  |  Lname  |  Fname
40001  |  Smith  |  John
40002  |  Jones  |  David
40003  |  Bryan  |  Kobe

上記のリストから項目をプログラムで選択するにはどうすればよいですか? たとえば、textBox に 40002 と入力すると、これが選択されます40002 | Jones | David

4

1 に答える 1

3

TextChanged次のイベントを処理する必要がありますTextBox

//TextChanged event handler for your textBox1
private void textBox1_TextChanged(object sender, EventArgs e) {
        ListViewItem item = listView1.Items.OfType<ListViewItem>()
                                     .FirstOrDefault(x => x.Text.Equals(textBox1.Text, StringComparison.CurrentCultureIgnoreCase));
        if (item != null){
            listView1.SelectedItems.Clear();
            item.Selected = item.Focused = true;
            listView1.Focus();//Focus to see it in action because SelectedItem won't look like selected if the listView is not focused.
        }
}

ListView.FindItemWithTextメソッドを使用することもできますが、アイテム text を開始する正確な文字列と一致することに注意してください。つまり、必要に応じて、大文字と小文字の区別を自分で処理する必要があります。

于 2013-09-08T16:58:36.227 に答える