2011-03-12 56 views
1

我無法理解下面的代碼:arraylist IndexOf在asp.net/c#中做了什麼?

if (IsPostBack) 
    { 
     int CheckBoxIndex; 
     ArrayList CheckBoxArray; 
     bool CheckAllWasChecked=false; 
     CheckBox chkAll = (CheckBox)GridView1.HeaderRow.Cells[0].FindControl("chkAll"); //chkAll is the id for checkbox on gridview 
     string checkAllIndex = "chkAll-" + GridView1.PageIndex; 
     if (chkAll.Checked) 
     {     
      if (CheckBoxArray.IndexOf(checkAllIndex) == -1) 
      { 
       CheckBoxArray.Add(checkAllIndex); 
      } 
     } 
     else 
     { 
      if (CheckBoxArray.IndexOf(checkAllIndex) != -1) 
      { 
       CheckBoxArray.Remove(checkAllIndex); 
       CheckAllWasChecked = true; 
      } 
     } 

什麼時候sampleArrayList.indexof(objectname)回報-1
我不明白?

請幫幫我!
謝謝你在期待

+0

下面的代碼甚至不會編譯告訴你'sampleArrayList'變量沒有被初始化。如果您想提出問題,請提供說明問題的完整工作代碼。 – 2011-03-12 18:34:47

+0

請在下次查詢文檔之前詢問。這只是簡單的方式:http://msdn.microsoft.com/en-us/library/system.collections.arraylist.indexof(v=VS.80).aspx – 2011-03-12 18:44:48

+0

@paul我問這個問題之前,我檢查了文檔,no在哪裏清楚當在arraylist中未找到指定的對象名時indexof返回什麼。它只表示「返回ArrayList或其一部分中第一次出現值的從零開始的索引。」我期待它會拋出一些例外。我GOOGLE了它,但沒有我在哪裏可以找到相關的搜索結果。所以我想問一個問題會澄清,而不是生活在一個模糊的地方。 – 2011-03-12 19:13:29

回答

2

當sampleArrayList沒有一個對象名元素sampleArrayList.IndexOf(CB1)將返回-1,如果它的發現

+0

如果它具有objectname元素它返回什麼? – 2011-03-12 18:34:00

1

IndexOf返回ArrayList中的對象的索引(位置),如果它不在ArrayList中則爲-1。

1

IndexOf(...)返回colleciont中搜索到的元素的位置(例如sampleArrayList)。如果您的列表中不包含你正在尋找我歸元 '-1'

在你的榜樣:

如果(sampleArrayList.IndexOf(CB1)== -1){

做一點事; }

如果你不接受'cb1',那麼'做點什麼'。