首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

WinForm ListView 獲取選中行綁定數據的值

     編輯:程式設計綜合問答

場景

ListView 綁定數據源(或手動添加項),點擊按鈕獲取當前選中行指定列的值。

核心代碼

private void btnGetSelected_Click(object sender, EventArgs e) {
    if (listView1.SelectedItems.Count > 0) {
        ListViewItem item = listView1.SelectedItems[0];
        // 假設第 0 列為 ID,第 1 列為 Name
        string id = item.SubItems[0].Text;
        string name = item.SubItems[1].Text;
        MessageBox.Show($"ID: {id}, Name: {name}");
    } else {
        MessageBox.Show("請先選中一行");
    }
}

// 若需在選中行變化時實時顯示
private void listView1_ItemSelectionChanged(object sender, ListViewItemSelectionChangedEventArgs e) {
    if (e.IsSelected) {
        txtValue.Text = e.Item.SubItems[1].Text; // 顯示第 1 列
    }
}

關鍵屬性

  • SelectedItems:返回選中行集合(ListView.SelectedListViewItemCollection)。
  • SubItems[index]:訪問該行第 index 列(第 0 列即 item.Text)。
  • FullRowSelect = true:設置 ListView 整行選中,便於用戶操作。

若 ListView 使用數據綁定

WinForms ListView 不直接支持數據綁定。常見做法:

  1. 手動填充:遍歷數據源 foreach(var o in list) { var item = new ListViewItem(o.Id.ToString()); item.SubItems.Add(o.Name); listView1.Items.Add(item); }
  2. 或改用 DataGridView,原生支持 DataSource 綁定,獲取當前行:dataGridView1.CurrentRow.Cells["Name"].Value。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved