2016-11-17 83 views
0

我是c#的新手。我正在嘗試製作如下圖所示的藍色區域列表: enter image description hereControl.Location.Y未返回正確位置

我已經使用了簡單的面板而不是列表框,因爲我需要爲每個條目添加控件。現在,您在圖像中看到的列表是我爲了測試其硬編碼值而做的。但是現在,當我試圖讓每個條目在最後一個條目下動態移動時,我無法實現它。我已經使用了Control.Location.Y,但它每次返回第二個條目的Y座標,並且條目彼此重疊。

下面是代碼:

public void enterItems (listingPanel list, int loc) 
    { 
     items.Add(list); 
     int lastIndex = items.Count - 1; 
     int newLoc = items[lastIndex].Location.Y + 52; 
     this.Controls.Add(items[lastIndex]); 
     if (lastIndex >= 1) 
      items[lastIndex].Location = new Point(0, newLoc); 
     Console.WriteLine("index: " + lastIndex + ", location Y: " + (items[lastIndex].Location.Y + 52) + " last loc: " + items[lastIndex].Location.Y + "Total: " + items.Count); 
    } 

這是),其被調用enterItems爲addItems(INT)的定義(方法:

private void addItems(int loc) 
    { 
     listingPanel lists = new listingPanel("Shashlik", Convert.ToString(20), Convert.ToString(2)); 
     listing.enterItems(lists, loc); 
    } 

這是調用爲addItems事件(int)方法:

private void sellBtn_Click(object sender, EventArgs e) 
    { 
     //for (int i = 0; i<1000; i = i+52) 
      addItems(0); 
    } 

感謝提前:)

回答

1

首先您將一個項目添加到列表中,然後您想將其相對於以前的項目進行定位。

但是因爲你添加項目清單後,獲得的最後一項的指標,實際上是相對於項目的定位到本身

請注意:如果你試圖通過把int lastIndex = items.Count - 1來解決該問題之前添加的項目,它當然會拋出異常,因爲lastIndex == -1,所以你必須提供一些第一項Y位置另一種方式。

+0

非常感謝您指出問題!我接下來做的只是在if條件中從lastIndex中減去1。 (lastIndex> = 1){items [lastIndex] .Location = new Point(0,items [lastIndex-1] .Location.Y + 52);} ; – user2978059