首页 > 解决方案 > 如何在 C# 的 TableLayoutPanel 中显示字典的内容?

问题描述

我需要在一个名为 TableLayoutPanelucOutputPredictionsResults的字典中显示名为的内容,predictionDictionary并在第一列中显示名称,在第二列中显示值。我的字典中的所有键和值都具有类型字符串。

我可以显示键和值,但不能按我要求的顺序显示

这是我所做的:

this.ucOutputPredictionsResults.RowCount = 0;
this.ucOutputPredictionsResults.ColumnCount = 0;

foreach (KeyValuePair<string, string> kvp in (_testExecution as TestExecutionAlveoGraph)
                                             .predictionDictionary)
{
   Label lb = new Label();
   lb.Text = kvp.Key;

   this.ucOutputPredictionsResults.Controls.Add(lb,
             this.ucOutputPredictionsResults.ColumnCount,
             this.ucOutputPredictionsResults.RowCount);

   Label valueLbl = new Label();
   valueLbl.Text = kvp.Value;

   this.ucOutputPredictionsResults.Controls.Add(valueLbl,
            this.ucOutputPredictionsResults.ColumnCount +1, 
            this.ucOutputPredictionsResults.RowCount);
}

但结果不是我所期望的:

在此处输入图像描述

标签: c#dictionarytablelayoutpanel

解决方案


尽管我同意 TaW 的观点,即您应该明确设置 TableLayoutPanel 并以更可控的方式添加控件,但您可以通过将 ColumnCount 设置为 2 并使用仅接收控件的 Add() 重载来解决“问题”。然后将按预期添加标签。

简化代码:

private void button1_Click(object sender, EventArgs e)
{
    this.ucOutputPredictionsResults.Controls.Clear();
    this.ucOutputPredictionsResults.RowCount = 0;
    this.ucOutputPredictionsResults.ColumnCount = 2;

    foreach (KeyValuePair<string, string> kvp in _testExecution)
    {
        Label lb = new Label();
        lb.Text = kvp.Key;

        this.ucOutputPredictionsResults.Controls.Add(lb);

        Label valueLbl = new Label();
        valueLbl.Text = kvp.Value;

        this.ucOutputPredictionsResults.Controls.Add(valueLbl);
    }
}

推荐阅读