简体   繁体   English

添加,编辑,从列表中删除项目<String>

[英]Add, Edit, Remove items from a List<String>

I have a list of Strings, List<String> . 我有一个字符串List<String>List<String>

I want to be able to open a form, showing the contents of this list, and allow the user to add, edit, and remove items from the list during run time. 我希望能够打开一个显示该列表内容的表单,并允许用户在运行时从列表中添加,编辑和删除项目。

I've been looking at ListView, but it isn't clicking for me. 我一直在查看ListView,但它并不是为我而点击。 I'm not sure if that's because it isn't the right solution or that I don't get it. 我不确定这是因为这不是正确的解决方案还是我不明白。

What is the proper solution for what I want to do? 我想做什么合适的解决方案?

Chuck 卡盘

You can use a list view and a context menu for your target: try this code: 您可以为目标使用list viewcontext menu :尝试以下代码:

    List<string> listofstring = new List<string>() {"A","B","C" };
    private void Form1_Load(object sender, EventArgs e)
    {
        FillLstView();
    }

    private void Additem_Click(object sender, EventArgs e)
    {
        listofstring.Add("New Item");
        FillLstView();
    }

    private void RemoveItem_Click(object sender, EventArgs e)
    {
        listofstring.RemoveAt(lstview.FocusedItem.Index);
        EditItem.Enabled = false;
        RemoveItem.Enabled = false;
        FillLstView();
    }

    private void lstview_SelectedIndexChanged(object sender, EventArgs e)
    {
            RemoveItem.Enabled = true;
            EditItem.Enabled = true;
    }

    private void EditItem_Click(object sender, EventArgs e)
    {
        string input = Microsoft.VisualBasic.Interaction.InputBox("Enter Edit", "Title", "Edited", 0, 0);
        if (input != "")
        {
            listofstring[lstview.FocusedItem.Index] = input;
            EditItem.Enabled = false;
            RemoveItem.Enabled = false;
            FillLstView();
        }
    }

    private void FillLstView()
    {
        lstview.Clear();
        foreach (var item in listofstring)
        {
            lstview.Items.Add(item);
        }
    }

Result 结果

在此处输入图片说明

Download Project 下载专案

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

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