在C#中动态添加控件到循环下

编程入门 行业动态 更新时间:2024-10-25 03:27:26
本文介绍了在C#中动态添加控件到循环下的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在开发Windows应用程序,我想在其中循环动态创建一些控件. 我正在尝试的代码是

I am developing a windows application where I want to create some controls dynamically inside a loop. The code I am trying is

private Label newLabel = new Label(); private int txtBoxStartPosition = 100; private int txtBoxStartPositionV = 25; for (int i = 0; i < 7; i++) { newLabel.Location = new System.Drawing.Point(txtBoxStartPosition, txtBoxStartPositionV); newLabel.Size = new System.Drawing.Size(70, 40); newLabel.Text = i.ToString(); panel1.Controls.Add(newLabel); txtBoxStartPositionV += 30; }

此代码仅生成一个带有文本7的标签,但是我想用它们各自的文本创建8个标签,我该怎么做?

This code is generating only one Label with text 7 but I want to create 8 Lables with their respective texts, how can I do this?

推荐答案

在您的循环中,您实质上是在更新同一Label的属性.如果要在每个步骤上创建一个新对象,请在循环内移动对象的创建:

In your loop you are essentially updating properties of the very same Label. If you want create a new one on each step, move creation of the object inside the loop:

private Label newLabel; for (int i = 0; i < 7; i++) { newLabel = new Label(); ...

如果想要 8 标签,您的for应该迭代8次,而不是7次,就像现在这样:

By the way if you want 8 labels - your for should iterate 8 times, not 7, as it does now:

for (int i = 0; i < 8; i++)

更多推荐

在C#中动态添加控件到循环下

本文发布于:2023-11-09 23:04:46,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1573680.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:控件   动态

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!