2012-10-07 45 views
0

我有這個函數將爲label list中的所有標籤創建一個Click eventlabel list是標籤的列表:Click evant出現錯誤:索引超出範圍。必須是非負數且小於集合的大小。參數名稱:索引

Label[] label = new Label[50]; // 50 is only a ramdom number, is not the real number of number of labels 

iilabelnumber of labels

orar[k]是包含某些字段列表:

static List<Orar> orar = new List<Orar>(); 

Orar是列表中的一類。該列表具有與ii(標籤數量)相同的字段數量。

這是創建Click事件的代碼。

for (int k = 0; k < ii; k++) 
      { 
       label[k].Click += (s, e) => 
       { 
        string materie = "", profesor = "", detali = "", zi = "", formatmaterie = "", sala = "", inputbox = "", inceputora = "", formatOra = "", saptamana = "", AMPM1 = "", p1 = ""; 
        int cand = 1, vl1 = 0, apm = 0; 

        materie = orar[k].materie; 
        profesor = orar[k].profesor; 
        detali = orar[k].detali; 
        zi = orar[k].zi; 
        formatmaterie = orar[k].formatmaterie; 
        sala = orar[k].sala; 
        inceputora = orar[k].inceputora; 
        formatOra = orar[k].formatora.ToString(); 
        saptamana = orar[k].saptamana; 
        AMPM1 = orar[k].apm; 

        vl1 = vl11; 
        cand = 1; 

        p1 = "Detali materie !"; 
        apm = 0; 

        inputbox = Programarii.InputAddOrar.Show(p1, ref materie, ref formatOra, ref sala, ref inceputora, ref formatmaterie, ref profesor, ref zi, ref detali, ref saptamana, ref vl1, ref cand, ref apm, ref AMPM1).ToString(); 
       }; 
      } 

問題是,不工作。我有這個錯誤:Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index

+1

哪條線拋出異常? – Steve

回答

1

我的猜測是你必須分配內存給列表中的orar元素。

所以:

orar.Add(new Orar()); 

然後做你的東西:

orar[i].someProperty = "SetProperty"; 

編輯: 捕獲的變量可以在這裏是原因。試試我的東西,做這個:

for (int k = 0; k < ii; k++) 
      { 
       int j = k ; //replace the k's in the lambdas with j 
       label[k].Click += (s, e) => 
       { 
        string materie = "", profesor = "", detali = "", zi = "", formatmaterie = "", sala = "", inputbox = "", inceputora = "", formatOra = "", saptamana = "", AMPM1 = "", p1 = ""; 
        int cand = 1, vl1 = 0, apm = 0; 

        materie = orar[j].materie; 
        profesor = orar[j].profesor; 
        detali = orar[j].detali; 
        zi = orar[j].zi; 
        formatmaterie = orar[j].formatmaterie; 
        sala = orar[j].sala; 
        inceputora = orar[j].inceputora; 
        formatOra = orar[j].formatora.ToString(); 
        saptamana = orar[j].saptamana; 
        AMPM1 = orar[j].apm; 

        vl1 = vl11; 
        cand = 1; 

        p1 = "Detali materie !"; 
        apm = 0; 

        inputbox = Programarii.InputAddOrar.Show(p1, ref materie, ref formatOra, ref sala, ref inceputora, ref formatmaterie, ref profesor, ref zi, ref detali, ref saptamana, ref vl1, ref cand, ref apm, ref AMPM1).ToString(); 
       }; 
      } 
+0

這不是問題,因爲我首先在列表後面創建標籤。 – AnDr3yy

+0

而且你肯定將對象分配給Label數組和List? –

+0

是的。分開。 – AnDr3yy

0

如果ii = 50然後更改k < ii - 1

+0

如果ii是50,k

+0

是的,但是有問題。對於所有標籤,click事件將顯示列表的最後一個元素,而不是他的元素。 – AnDr3yy

相關問題