C# 从列表视图控件中获取价值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14708244/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 12:45:13  来源:igfitidea点击:

Getting value from listview control

c#

提问by user2006506

Need help selecting the value from custID column in the ListView so that I can retrieve the value from the database and display it in the TextBoxes.The SelectedIndex not working in c#

需要帮助从 ListView 的 custID 列中选择值,以便我可以从数据库中检索值并将其显示在 TextBoxes 中。 SelectedIndex 在 c# 中不起作用

Thanks

谢谢

http://img713.imageshack.us/img713/133/listview.jpg

http://img713.imageshack.us/img713/133/listview.jpg

My Code

我的代码

private void yourListView_SelectedIndexChanged(object sender, EventArgs e)
{
    if (yourListView.SelectedIndex == -1)
        return;
    //get selected row
    ListViewItem item = yourListView.Items[yourListView.SelectedIndex];
    //fill the text boxes
    textBoxID.Text = item.Text;
    textBoxName.Text = item.SubItems[0].Text;
    textBoxPhone.Text = item.SubItems[1].Text;
    textBoxLevel.Text = item.SubItems[2].Text;
}

采纳答案by algreat

ListView doesn't have property SelectedIndex. You should use SelectedItemsor SelectedIndices.

ListView 没有属性SelectedIndex。您应该使用SelectedItemsSelectedIndices

So you can use this:

所以你可以使用这个:

private void yourListView_SelectedIndexChanged(object sender, EventArgs e)
{
    if (yourListView.SelectedItems.Count == 0)
        return;    

    ListViewItem item = yourListView.SelectedItems[0];
    //fill the text boxes
    textBoxID.Text = item.Text;
    textBoxName.Text = item.SubItems[0].Text;
    textBoxPhone.Text = item.SubItems[1].Text;
    textBoxLevel.Text = item.SubItems[2].Text;
}

I suggested here that property MultiSelectis set to false.

我在这里建议将属性MultiSelect设置为false.

回答by Eran Peled

C# and WPF use this:

C# 和 WPF 使用这个:

private void lv_yourListView_SelectedIndexChanged(object sender, EventArgs 
e)
{
    if (yourListView.SelectedItems.Count == 0)
        return;    

     var item = lvb_listInvoices.SelectedItems[0];
     var myColumnData = item.someField; //use whatever you want
}