[英]Adding a textbox C#
在Program.cs中,我添加了:
public void displayControls()
{
TextBox tb = new TextBox();
tb.Text = "Enter";
tb.Location = new Point(300, 300);
tb.Size = new Size(300, 300);
tb.Visible = true;
tb.Show();
tb.BringToFront();
}
然后在:
static void Main(string[] args)
{
this.displayControls();
}
但這是行不通的。 我是否需要從Form.cs訪問表單實例並將其添加到該實例? 我需要什么使該文本框在表單中可見?
謝謝。
看來您的目標是WinForm應用程序。 您需要在Form.cs
執行此Form.cs
,可以在Form_Load
事件中執行以下操作:
private void Form1_Load(object sender, EventArgs e)
{
TextBox tb = new TextBox();
tb.Text = "Enter";
tb.Location = new Point(300, 300);
tb.Size = new Size(300, 300);
tb.Visible = true;
this.Controls.Add(tb); //here add it to the current form instance
}
您應該嘗試將與UI相關的元素放在Forms.cs中 。 它更容易,並且具有更好的設計。
您應該檢查一下,如果您右鍵單擊Visual Studio解決方案上的Form1.cs元素,則可以訪問“查看代碼”選項。 從這里您可以看到與UI相關的代碼。
您將看到這個簡單的類定義
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
}
但是,當您檢查InitializeComponent方法時,可以看到使文本框出現的說明。 注意不要在Form1.Designer.cs中編寫代碼,因為它每次生成時都會自動生成代碼
displayControls
應該是形式的方法,而不是程序 。 另外,您將需要:
this.Controls.Add(tb);
確保正確處理
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.