2016-12-02 30 views
-3

我宣佈我的數組像這樣使用數組,中如果知道情況,如果該指數是在C#空

string[] timeArrivalArray = new string[10]; 

現在,讓我們假設每點擊添加按鈕,東西插入那裏。

但是我想使用if條件到某個索引。 我想用這樣的

if (timeArrivalArray[] == [2]) { 
} 

現在,每當我點擊button,則timeArrivalArray[]會檢查它是否已經在第二個索引,然後執行代碼。 tl; dr我只想使用if條件到第二個索引,這怎麼可能?

編輯
我的問題是它在第一個增量中拋出excemption。我有一個button和從某些變量插入的東西。然而,上面的代碼插入到該

if (timeArrivalArray[] == [2]) { 
    //*insert variable this* 
} else { 
    // *insert variable that* 
} 

編輯2
是的,它不是正確的語法,我只知道如何做到這一點。但我的問題的根源是這

DateTime theCalcu = DateTime.ParseExact(timeArrivalArray[2], "h:mm tt", System.Globalization.CultureInfo.InvariantCulture); 

它扔我String reference not set to an instance of a String. 也許是因爲他無法找到任何索引前面的索引。 任何建議都可以。

+0

目前還不清楚你在問什麼。請添加一個代碼,顯示按鈕應該執行的操作,並重新說明問題並說明問題所在。 –

+0

我不明白這一點。你只是想像'if(timeArrivalArray [2] ==「無論」)'? – Jens

+0

先生們,我編輯了我的問題。對於這個問題抱歉,但我不能直想。 – Fiendcoder1

回答

0

儘管我可以從你的帖子理解這裏是我能想到的邏輯。你可以讓我知道什麼不起作用。

string[] timeArrivalArray = new string[10]; 
public void Button1_Click(object sender, EventArgs e) 
     { 
      if (timeArrivalArray[2] == null) 
      { 
       //keep inserting into the array since 2nd index is null 
      } 
      else if (timeArrivalArray[2] != null && timeArrivalArray[2] == "someInputValue") 
      { 
       //2nd index is non null and some existing value found 
       //so do something else 
      } 
      else 
      { 
       //2nd index isn't null but input value wasn't found so keep inserting 
      } 
     } 
+0

檢查null並不是很有用,因爲C#的'new'會將所有數組初始化爲空字符串。 – t0mm13b

+2

Nope @ t0mm13b。他們將被初始化爲null。字符串是一個引用類型。 – RBT

+1

woop ...我的壞,仍然會更好地使用'String.IsNullOrEmpty' [MSDN](https://msdn.microsoft.com/en-us/library/system.string.isnullorempty.aspx) – t0mm13b

0

每當我按一下按鈕。 timeArrivalArray []將檢查它是否已經在第二個索引[...]我只是想使用第二個索引的if條件

這聽起來像你想要每次計算索引發生點擊。如果是這樣,你應該指定一個索引變量超出單擊事件的範圍:

string[] timeArrivalArray = new string[10]; 

int index = 0; 

public void Button1_Click(object sender, EventArgs e) 
{ // make sure you are not running out of bounds  
    if(index < timeArrivalArray.Length) 
    {  
     if(index == 2) 
     { 
      timeArrivalArray[index] = //*insert variable this* 
     } 
     else 
     { 
      // *insert variable that* 
     }   
    } 

    index ++; // walk to the next position  
}