在列表框中选择项目C# [英] select item in list box C#
问题描述
我正在使用C#(Windows窗体应用程序)
我的程序中有 listview 这样的
Id姓名数量
001 AAA 111
002 BBB 222
003 CCC 333
004 DDD 444
我是C#的新手所以我想在文本框中输入名称并点击搜索按钮然后选择名称列中的<等值和显示我的标签中的所有数据然后我使用此代码检查列表视图列值但是我需要知道其他部分(选择相等的数据坐在我的标签中)
EX - 我搜索 AAA 然后我想要我的
lable1的值 001
lable2的值< b> AAA
lable3的值 111
foreach (ListViewItem item in listview1.It ems)
{
if (item.SubItems [ 2 ]。文字= = name.Text)
{
// 此部分的任何想法
}
}
提前感谢
< blockquote>有一个属性:
可以找到其他文档信息 here [ ^ ]。
我修改了你的代码示例:
int searchIndex = 0 ; // 使用计数器了解您当前所在的行
foreach (ListViewItem item in listview1.Items)
{
if (item.SubItems [ 2 ]。Text == name.Text)
{ // 如果找到文本,请在当前索引处选择行
listview1.Items [searchIndex] .Selected = 真跨度>;
label1.Text = item.SubItems [ 0 ]。文字;
label2.Text = item.SubItems [ 1 ]。文字;
label3.Text = item.SubItems [ 2 ]。文字;
}
其他
{ // 如果找不到文本,则取消选择当前索引处的行
listview1.Items [searchIndex] .Selected = false ;
}
// 之后,增加searchIndex ++ 1
searchIndex ++;
}
在ListView中名称列是第二列,因此其索引为1.
foreach (ListViewItem item in listView1.Items)
{
if (!string.IsNullOrEmpty(item.Text)) // 检查项目值不是空或空
{
如果(项目。 SubItems [ 1 ]。Text == name.Text)
{
label1.Text = item.SubItems [ 0 跨度>]文本。
label2.Text = item.SubItems [ 1 ]。文字;
label3.Text = item.SubItems [ 2 ]。文字;
}
}
}
i'm using C# (windows form application)
I have a listview in my program like this
Id Name Quantity
001 AAA 111
002 BBB 222
003 CCC 333
004 DDD 444
i'm new to C# So i want to when i input name in textbox and click the search button then select the equal value in name column and show all data in my lables then i use this code to check listview column value but i need any idea to else part (select equal data sat and display in my lables)
EX - i search AAA then i want to my
lable1's value 001
lable2's value AAA
lable3's value 111
foreach (ListViewItem item in listview1.Items)
{
if (item.SubItems[2].Text == name.Text)
{
// any idea to this part
}
}
Thank in advance
There is a property for this:
Additional documentation information can be found here[^].
I modified your code sample a bit:
int searchIndex = 0; //Use a counter to know on which row you currently are foreach (ListViewItem item in listview1.Items) { if (item.SubItems[2].Text == name.Text) {//If text is found, select row at the current index listview1.Items[searchIndex].Selected = true; label1.Text = item.SubItems[0].Text; label2.Text = item.SubItems[1].Text; label3.Text = item.SubItems[2].Text; } else {//If text is not found, deselect row at the current index listview1.Items[searchIndex].Selected = false; } //afterwards, increase searchIndex ++1 searchIndex++; }
In your ListView "Name" Column is second Column so its index is 1.
foreach (ListViewItem item in listView1.Items) { if (!string.IsNullOrEmpty(item.Text))//Check Item value is not Null or Empty { if (item.SubItems[1].Text == name.Text) { label1.Text = item.SubItems[0].Text; label2.Text = item.SubItems[1].Text; label3.Text = item.SubItems[2].Text; } } }
这篇关于在列表框中选择项目C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!