2014-04-18 151 views
0

所以我能夠通過索引刪除,但我的問題是否有辦法通過鍵入對象名稱來刪除對象?例如:鍵入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 
    } 

回答

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

似乎並沒有做任何事情 – TheBoringGuy

+0

Nvm讀它錯了大聲笑 – TheBoringGuy

0

我寧願列表,而不是數組,

 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"); 
     } 
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 
+0

如何將新對象插入特定索引? – TheBoringGuy

+0

anwer編輯插入項目 –