标签控件未显示在Winform C#上

时间:2018-06-29 08:51:50

标签: c#

我有这段代码,我必须从数据库中提取数组中的5条记录。我必须在每个标签上显示每个记录。因此,我生成了运行时标签,使用split函数拆分数组,然后在每个标签上显示其中的每个标签。当我运行此代码并单击按钮时,仅显示一个值。此代码有什么问题?

private void button1_Click(object sender, EventArgs e)
{

        for(int i=0;i<5;i++)
        {
            addlabel(i);

        }

    for (int i1 = 0; i1 < 5; i1++)
    {
        addlabel1(i1);
    }
}

void addlabel(int i)
{
    string cons = ConfigurationManager.ConnectionStrings["dbx"].ConnectionString;
    SqlConnection con = new SqlConnection(cons);
    con.Open();
    string str = "SELECT * FROM marks  WHERE idno = " + textBox1.Text + "";

    SqlCommand com = new SqlCommand(str, con);
    SqlDataReader reader = com.ExecuteReader();
    while (reader.Read())
    {
        var input = reader["subjects"].ToString();
        var split = input.Split(new string[] { ",", " " }, StringSplitOptions.RemoveEmptyEntries); 
        for (int j = 0; j < split.Length; j++)
        {
            Label l = new Label();
            l.Name = "label" + i.ToString();
            l.Text = split[j];
            l.Location = new Point(232, 100);
            this.Controls.Add(l);
        }

    }

}

void addlabel1(int i1)
{
    string cons = ConfigurationManager.ConnectionStrings["dbx"].ConnectionString;
    SqlConnection con = new SqlConnection(cons);
    con.Open();
    string str = "SELECT * FROM marks  WHERE idno = " + textBox1.Text + "";

    SqlCommand com = new SqlCommand(str, con);
    SqlDataReader reader = com.ExecuteReader();
    while (reader.Read())
    {

        var input1 = reader["smarks"].ToString();
        var split1 = input1.Split(new string[] { ",", " " }, StringSplitOptions.RemoveEmptyEntries);

        for (int z = 0; z < split1.Length; z++)
        {
            Label l1 = new Label();
            l1.Name = "label" + i1.ToString();
            l1.Text = split1[z];
            l1.Location = new Point(353, 100);
            this.Controls.Add(l1);

        }
    }

}

有什么建议吗?

1 个答案:

答案 0 :(得分:0)

您可能想要这样的东西(将值作为表格打印出来):

 int left = 232;
 int top = 100;
 int step_x = 80;
 int step_y = 20;

 // outer loop - lines
 while (reader.Read()) {
   var split = Convert.ToString(reader["subjects"])
     .Split(new string[] { ",", " " }, StringSplitOptions.RemoveEmptyEntries); 

   // inner loop - columns
   for (int j = 0; j < split.Length; j++) {
     new Label() {
       Name = $"label{i}",
       Text = split[j],
       // Notice "top + step_y * j" - label after label
       Location = new Point(left, top + step_y * j), 
       Parent = this, // equal to this.Controls.Add(l); 
     };
   }

   left += step_x;
 }