问题描述
我要显示从数据库到列表视图的所有记录
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
如何从上面的列表中以编程方式选择一个项目?例如,我在文本框中键入40002,然后将其选择为40002 | Jones | David
您必须处理TextBox
的TextChanged
事件:
//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
方法,但是请注意它与以项目文本开头的确切字符串匹配,这意味着您必须自己处理大小写敏感情况. /p>
I have this to show all records from database to listview
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() }));
}
}
}
}
For example I have this result:
EmpID | Lname | Fname
40001 | Smith | John
40002 | Jones | David
40003 | Bryan | Kobe
How I will programmatically select an item from the list above? For example I type 40002 in the textBox then this will be selected 40002 | Jones | David
You have to handle the TextChanged
event of your 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.
}
}
You can also use ListView.FindItemWithText
method, but notice that it matches the exact string which starts the item text, that means you have to handle the case-sensivity yourself in case you want.
这篇关于以编程方式在ListView中选择项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!