操纵索引中的对象

时间:2014-04-18 04:35:27

标签: c# arrays object listbox indexing

所以我能够通过索引删除,但我的问题是我可以通过键入对象名称来删除对象吗? 例如:输入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
    }

3 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

我更喜欢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");
        }

答案 2 :(得分:0)

您需要使用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