c# - WinForms:使用 c# 添加控件
问题描述
我是 c# 新手,我知道如何动态添加控件,但我不知道如何将该控件设置为this.[control_name]
. 请注意,这里this
是Form
.
这可以用静态方法完成private System.Windows.Forms.[Control_type] [control-name];
,但我将如何从方法中做到这一点,以便我以后可以声明this.[control-name] = [variable]
?
请注意,variable
类似于new TextBox()
;
解决方案
var txt = new TextBox(); //txt is the variable you are looking for
Form1.Controls.Add(txt); //added it to the form
现在您可以通过以下方式访问它txt
:
txt.Location = new Point(0,0);
txt.Visible = true;
如果您在方法中创建控件(正如您在评论中提到的),您可以返回并使用它,如下所示:
public TextBox AddTextBox()
{
var txt = new TextBox();
Form1.Controls.Add(txt);
return txt;
}
var newTxt = AddTextBox();
newTxt.Location = new Point(0,0);
newTxt.Visible = true;
推荐阅读
- python - pandas 为每个多索引组选择前 N 个值
- optimization - 谷歌优化给出错误:编辑器页面 URL 与将应用的前一个页面的定位规则匹配
- ruby-on-rails - Axlsx 导轨上的缩进
- python - Leetcode中如何理解Python链表的数据结构
- swift - 为什么我收到错误“UIImageView”类型的值没有成员“sd_setShowActivityIndicatorView”
- javascript - 使用 Axios 将整个 HTML 项目加载到 VueJS 组件中
- macos - ffmpeg 将 .vob 转换为 .mp4 --- 颜色被洗掉了
- typescript - DocDB 的 SubnetGroup.fromSomething()?
- html - 为什么 Disabled 在以下 html/angular 代码中不起作用?
- c# - C# 随机化继承的类而不进行硬编码