简体   繁体   English

如何编辑列表视图中的项目

[英]How to edit items in a listview

I want to be able to edit the items that I have added to my listview. 我希望能够编辑我添加到列表视图中的项目。

The listview items were added through a textbox, datetimepicker, and a combobox. listview项目是通过文本框,datetimepicker和组合框添加的。

The listview has three columns. 列表视图有三列。 What I want is: When I click on the listview item, (the listview selects all the columns) and then click on the edit button, then the textbox is replaced with column one, the datetimepicker is replaced with the date of column 2, and the combobox is replaced with column 3. 我想要的是:当我点击listview项目时,(列表视图选择所有列)然后单击编辑按钮,然后文本框被第一列替换,datetimepicker被替换为第2列的日期,并且组合框用第3列替换。

Then I can edit the textbox, date, or the combobox items and when I click the save button, then the listview item is updated. 然后我可以编辑文本框,日期或组合框项目,当我单击保存按钮时,列表视图项目将更新。

Since you want to use separate edit controls and buttons to update there is no need to overlay the listview subitems with controls. 由于您要使用单独的编辑控件和按钮进行更新,因此无需使用控件覆盖listview子项。

Here is example code to load the controls from the 1st selected item and to update that Item in the ListView : 下面是从第一个选定项加载控件并在ListView更新该Item示例代码:

    private void lv_edit_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (lv_edit.SelectedIndices.Count > 0)
        {
            var lvi = lv_edit.SelectedItems[0];
            tb_col1.Text = lvi.SubItems[0].Text;
            date_col2.Value = Convert.ToDateTime(lvi.SubItems[1].Text);
            combo_col3.SelectedIndex = combo_col3.FindStringExact(lvi.SubItems[2].Text);
        }
    }

    private void cb_updateItem_Click(object sender, EventArgs e)
    {
        if (lv_edit.SelectedIndices.Count > 0)
        {
            var lvi = lv_edit.SelectedItems[0];
            lvi.SubItems[0].Text = tb_col1.Text;
            lvi.SubItems[1].Text = date_col2.Value.ToString("dddd, dd. MMMM yyyy");
            lvi.SubItems[2].Text = combo_col3.SelectedItem.ToString();
        }
    }

Note that SubItems[0].Text is the same as Items[0].Text . 请注意, SubItems[0].TextItems[0].Text

Also note that the code assumes that all items have all three fields and their values are all valid, ie that the conversion and the find will work. 另请注意,代码假定所有项都包含所有三个字段,并且它们的值都是有效的,即转换和查找将起作用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM