簡體   English   中英

在C#的“列”中格式化動態創建的單選按鈕

[英]Format dynamically created Radio buttons in Columns in c#

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

現在,每個新的單選按鈕都位於上一個按鈕的下方。 如何在例如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;
    };
}

如何使用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;
    };
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM