2017-06-13 38 views
0

我正在爲數組/列表中的每個元素以編程方式創建單選按鈕,並將它們放置在窗體中。動態創建的格式c中的列中的單選按鈕#

現在每個新的單選按鈕都放在前一個按鈕下面。我怎樣才能設法開始一個新的列後,例如4/5單選按鈕?新列應顯示在前面的單選按鈕的右側。

這是我到目前爲止的代碼:

for (int i = 0; i < startShapes.Count; i++) 
{ 
    RadioButton rdb = new RadioButton(); 
    rdb.Text = startShapes.Values.ElementAt(i).Equals("") ? startShapes.Keys.ElementAt(i) : startShapes.Values.ElementAt(i); 
    rdb.Size = new Size(100, 30); 
    this.Controls.Add(rdb); 
    rdb.Location = new Point(45, 70 + 35 * i); 
    rdb.CheckedChanged += (s, ee) => 
    { 
     var r = s as RadioButton; 
     if (r.Checked) 
      this.selectedString = r.Text; 
    }; 
} 
+0

開始新的列在哪裏?你爲什麼不分享你迄今爲止所做的一切? – Abhishek

+0

增加下一個單選按鈕的左值? – Gusman

+0

@Abhishek的帖子已更新! – dnks23

回答

1

如何使用TableLayoutPanel中?

 Dictionary<string, string> startShapes = new Dictionary<string, string>(); 
     for(int i=0;i<20;i++) 
      startShapes.Add("Shape " +i, "Shape " +i); 
     int row = 0; 
     int col = 0; 
     tableLayoutPanel1.RowStyles.Clear(); 
     tableLayoutPanel1.ColumnStyles.Clear(); 
     tableLayoutPanel1.ColumnStyles.Add(new ColumnStyle(SizeType.AutoSize)); 
     tableLayoutPanel1.RowCount= 0; 
     tableLayoutPanel1.ColumnCount = 1; 

     foreach (var kvp in startShapes) 
     { 
      tableLayoutPanel1.RowStyles.Add(new RowStyle(SizeType.AutoSize)); 
      tableLayoutPanel1.RowCount++; 
      RadioButton rdb = new RadioButton(); 
      rdb.Text = string.IsNullOrEmpty(kvp.Value) ? kvp.Key : kvp.Value; 
      rdb.Size = new Size(100, 30); 
      rdb.CheckedChanged += (s, ee) => 
      { 
       var r = s as RadioButton; 
       if (r.Checked) 
        this.selectedString = r.Text; 
      }; 
      tableLayoutPanel1.Controls.Add(rdb, col, row); 
      row++; 
      if (row == 5) 
      { 
       col++; 
       row = 0; 
       tableLayoutPanel1.ColumnStyles.Add(new ColumnStyle(SizeType.AutoSize)); 
       tableLayoutPanel1.ColumnCount++; 
      } 
     } 

如果你真的需要你的解決方案:

int left = 45; 
int idx = 0; 
for (int i = 0; i < startShapes.Count; i++) 
{ 
    RadioButton rdb = new RadioButton(); 
    rdb.Text = startShapes.Values.ElementAt(i).Equals("") ? startShapes.Keys.ElementAt(i) : startShapes.Values.ElementAt(i); 
    rdb.Size = new Size(100, 30); 
    this.Controls.Add(rdb); 
    rdb.Location = new Point(left, 70 + 35 * idx++); 
    if (idx == 5) 
    { 
     idx = 0; // reset row 
     left += rdb.Width + 5; // move to next column 
    } 
    rdb.CheckedChanged += (s, ee) => 
    { 
     var r = s as RadioButton; 
     if (r.Checked) 
      this.selectedString = r.Text; 
    }; 
}