9

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

谢谢

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

我的代码

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;
}
4

2 回答 2

18

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

所以你可以使用这个:

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;
}

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

于 2013-02-05T13:18:38.340 回答
2

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
}
于 2017-12-05T17:28:50.677 回答