【问题标题】:Display the selected row from listview to textBox?将列表视图中的选定行显示到文本框?
【发布时间】:2013-07-10 01:52:14
【问题描述】:

如何将列表视图中的选定行显示到文本框?

这就是我做 int dataGridView 的方式:

private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
    dataGridView1.Rows[e.RowIndex].ReadOnly = true;
    if (dataGridView1.SelectedRows.Count != 0)
    {
        DataGridViewRow row = this.dataGridView1.SelectedRows[0];
        EmpIDtextBox.Text = row.Cells["EmpID"].Value.ToString();
        EmpNametextBox.Text = row.Cells["EmpName"].Value.ToString();
    }
}

我试过了:

private void listView1_SelectedIndexChanged(object sender, EventArgs e)
{
    ListViewItem item = listView1.SelectedItems[0];
    if (item != null)
    {
        EmpIDtextBox.Text = item.SubItems[0].Text;
        EmpNametextBox.Text = item.SubItems[1].Text;
    }
}

【问题讨论】:

  • 代码应该可以工作,实际问题是什么?
  • IndexOutOfRangeException可能会出现一些异常,因为有时ListView中没有选中项。
  • 将一行改为ListViewItem item = listView1.SelectedItems.Count > 0 ? listView1.SelectedItems[0] : null; 将涵盖超出范围的问题。

标签: c# winforms listview textbox


【解决方案1】:

//在c#中选择行列表视图检查

foreach (listViewItem itemRow in taskShowListView.Items) {

            if (itemRow.Items[0].Checked == true)
            {

                int taskId = Convert.ToInt32(itemRow.SubItems[0].Text);

                string taskDate = itemRow.SubItems[1].ToString();
                string taskDescription = itemRow.SubItems[2].ToString();



            }


        }

【讨论】:

  • 欢迎来到 StackOverflow。你能详细说明你的答案吗?
【解决方案2】:

您可能需要先检查是否存在 SelectedItem。 When the selection changed, ListView would actually unselect the old item then select the new item, hence triggering listView1_SelectedIndexChanged twice.除此之外,您的代码应该可以工作:

private void listView1_SelectedIndexChanged(object sender, EventArgs e)
{
    if (listView1.SelectedItems.Count > 0)
    {
        ListViewItem item = listView1.SelectedItems[0];
        EmpIDtextBox.Text = item.SubItems[0].Text;
        EmpNametextBox.Text = item.SubItems[1].Text;
    }
    else
    {
        EmpIDtextBox.Text = string.Empty;
        EmpNametextBox.Text = string.Empty;
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-19
    • 2012-10-03
    相关资源
    最近更新 更多