操纵索引中的对象

本文关键字:对象 索引 操纵 | 更新日期: 2023-09-27 17:58:56

所以我可以通过索引删除,但我的问题是,有没有一种方法可以通过键入对象名称来删除对象?例如:输入sara按钮,它会从我的索引中删除那个对象。我的第二个问题是,有没有一种方法可以将一个新对象插入到我想要的索引中?

我是windows形式的,如果你能帮助我或链接我的教程,我会非常棒。

    public Form1()
    {
        InitializeComponent();
    }
    private void Form1_Load(object sender, EventArgs e)
    {
        object[] names={"Sara", "Bill", "Martin", "Suasan", "Don"};
        listBox1.Items.AddRange(names);
    }
    private void btnRemoveByIndex_Click(object sender, EventArgs e)
    {
        //remove by index 
        int index = int.Parse(txtIndex.Text);
        if (index >= 0 && index < listBox1.Items.Count)
        {
                listBox1.Items.RemoveAt(index);
        }
        listBox1.ClearSelected();
    }
    private void btnRemoveByItem_Click(object sender, EventArgs e)
    {
        //remove objects
    }
    private void btnSpecIndex_Click(object sender, EventArgs e)
    {
       //insert new object
    }

操纵索引中的对象

if (listBox1.SelectedItem != null)
    listBox1.Items.Remove(listBox1.SelectedItem);

我更喜欢List而不是Array,

        List<string> Names;
        public Form1()
        {
            InitializeComponent();
            Names = new List<string>();
            Names.Add("Sara");
            Names.Add("Bill");
            Names.Add("Martin");
            Names.Add("Susan");
            Names.Add("Don");
            listBox1.DataSource = Names;
        }
        private void button1_Click(object sender, EventArgs e)
        {
            if (listBox1.SelectedItem == "Sara")
            {
                Names.Remove("Sara");
            }
            //To Insert a new Name at specific index say 1st
            Names.Insert(1, "Sample");
        }

您需要使用listBox1.Items.Remove

 object[] names = { "Sara", "Bill", "Martin", "Suasan", "Don" };
            ListBox listBox1 = new ListBox();
            listBox1.Items.AddRange(names);
            // give a same names value to remove item from listbox 
            listBox1.Items.Remove("Sara");

如果您想在特定索引中插入项目,请使用

listBox1.Items.Insert(0, "tet");  //0 is index and "tet" is value