WinForm点击鼠标显示文本失败,请求排查代码问题
问题:WinForms中动态创建的TextBox不显示
你在Form的MouseClick事件中编写了以下代码,但创建的TextBox并未显示:
private void Form1_MouseClick(object sender, MouseEventArgs e) { int x = e.X; int y = e.Y; TextBox TextWithNumber = new TextBox(); TextWithNumber.Width = 100; TextWithNumber.Height = 100; TextWithNumber.Location = new Point(x, y); TextWithNumber.Text = "TEXT"; TextWithNumber.BackColor = Color.Green; TextWithNumber.ForeColor = Color.Red; }
问题原因
你成功实例化了TextBox对象并设置了各项属性,但没有将这个TextBox添加到窗体的控件集合中。WinForms只有当控件被加入到容器(比如当前Form)的Controls集合时,才会在界面上渲染并显示该控件。
解决方案
在方法末尾添加一行代码,将创建好的TextBox添加到窗体的控件集合中:
private void Form1_MouseClick(object sender, MouseEventArgs e) { int x = e.X; int y = e.Y; TextBox TextWithNumber = new TextBox(); TextWithNumber.Width = 100; TextWithNumber.Height = 100; TextWithNumber.Location = new Point(x, y); TextWithNumber.Text = "TEXT"; TextWithNumber.BackColor = Color.Green; TextWithNumber.ForeColor = Color.Red; // 添加此行代码 Controls.Add(TextWithNumber); }
内容的提问来源于stack exchange,提问作者user21396294
相关产品推荐
相关产品推荐

