2017-05-09 91 views
-1

我有兩個listbox(listboxlong和listboxlat),我有圖片框來繪製值(通過使用timer(timer1))在列表框中。我想參加listboxes值爲每一行picturebox x和y值(listboxlong爲x值,listboxlat爲y值)。即使我嘗試foreach循環,我無法實現它。如果有一個與「AND」一起使用的代碼,請讓我知道。謝謝你的幫助。這是我的代碼;如何將AND添加到foreach循環?

private void timer1_Tick(object sender, EventArgs e) 
    { 
     pictureBoxPath.Refresh(); 
     listBoxLong.Items.Add(gPathBoylam); 
     listBoxLat.Items.Add(gPathEnlem); 
    } 
    private void pictureBoxPath_Paint(object sender, PaintEventArgs e) 
    { 
     SolidBrush myBrush = new SolidBrush(Color.Red); 

     foreach (var item in listBoxLat.Items) 
     { 
       foreach (var item2 in listBoxLong.Items) 
      { 
      e.Graphics.DrawEllipse(myPen, Convert.ToInt16(item), Convert.ToInt16(item2), 2, 2); 
      } 

     }   

    } 
+0

那麼,你會得到什麼樣的錯誤,「AND」問題對我來說沒有意義,但無論你看到什麼問題?我看到你試圖將一個列表框項目作爲一個int ...沒有嘗試過,但我想象你應該在item.value之後.... – Trey

+0

請提供一個更清晰的描述你的問題。 – MetaColon

+0

foreach循環意味着只做一件事,一件事:循環遍歷某些集合中的每個元素。它不能也不能檢查'foreach(..)'部分中的另一個條件。如果你想循環2個集合,你需要像他們一樣嵌套它們。或者,使用不同的循環(例如for)。 –

回答

1

你需要認識到你的qustion不是很清楚,但在閱讀您的意見和專門找這樣的:

foreach(var item in listBoxLat.Items && var item2 in listBoxLong.Items) 
{ 
    e.Graphics.DrawEllipse(myPen, Convert.ToInt16(item), Convert.ToInt16(item2), 2, 2); 
} 

我想你想一個列表的第一個項目運行到第一項到另一個列表並繼續。你想讓它們同步。

所以更好的方法是使用元組來存儲元組列表。你需要了解「Graphics.DrawEllipse」是如何工作的。所以我把下面的文檔總結。

所以下面的代碼可能工作,我無法測試這個,因爲我現在正在工作。

List<Tuple<int, int>> myTuple = new List<Tuple<int, int>>(); 

private void timer1_Tick(object sender, EventArgs e) 
{ 
    pictureBoxPath.Refresh(); 

    myTuple.Add(new Tuple<int, int>(gPathBoylam, gPathEnlem)); 
} 

// 
// Summary: 
//  Draws an ellipse defined by a bounding rectangle specified by coordinates 
//  for the upper-left corner of the rectangle, a height, and a width. 
// 
// Parameters: 
// pen: 
//  System.Drawing.Pen that determines the color, width, 
//  and style of the ellipse. 
// 
// x: 
//  The x-coordinate of the upper-left corner of the bounding rectangle that 
//  defines the ellipse. 
// 
// y: 
//  The y-coordinate of the upper-left corner of the bounding rectangle that 
//  defines the ellipse. 
// 
// width: 
//  Width of the bounding rectangle that defines the ellipse. 
// 
// height: 
//  Height of the bounding rectangle that defines the ellipse. 
// 
// Exceptions: 
// System.ArgumentNullException: 
//  pen is null. 
private void pictureBoxPath_Paint(object sender, PaintEventArgs e) 
{ 
    Pen myPen = new Pen(Color.Red, 3); // Create pen 

    if(myTuple != null && myTuple.Any()) 
    { 
     foreach (var tuple in myTuple) 
     { 
      Rectangle rect = new Rectangle(Convert.ToInt16(tuple.Item1), Convert.ToInt16(tuple.Item2), 2, 2); // Create rectangle for ellipse 

      e.Graphics.DrawEllipse(myPen, rect); // Draw ellipse to screen 
     } 
    } 
} 
+0

非常感謝你安德魯它是什麼我想要的。只是在你的代碼中有一個小錯誤suc; 'foreach(var tuple in myTuple)'應該代替'foreach(var varpleple in myValues)' – Quanthema

+0

編輯和修正。 ;) –

相關問題