我正在開發一個個人專案,我正在構建一個筆記生成器,并且每次單擊按鈕時都會動態創建這個 TextBox,它可以正常作業,就像我預期的那樣,但是當我嘗試命名每個這些時,事情變得很奇怪通過使用回圈將文本框更改為不同的名稱,Name = "Note" i其中i回圈變數。
所以我期望發生的是每個 TextBox 名稱都類似于,Note1 Note2 Note3 ... 但是當我在用于生成 TextBox 的同一回圈中將每個 TextBox 名稱檢索到 MessageBox 時,MessageBox 會拋出這個:Note 1 Note 1 Note 1 ...而不是當我按了三次按鈕。
int curr = 0;
private void guna2Button1_Click(object sender, EventArgs e) {
int top = 25;
int h_p = 170;
curr ;
for(int i=1; i<curr 1; i ) {
// Notes
var new_note = new Guna2TextBox() {
Text = "Title\n",
Name = "Note" i,
Multiline = true,
AcceptsTab = true,
AcceptsReturn = true,
WordWrap = false,
ScrollBars = ScrollBars.Vertical,
Width = 220,
Height = 110,
BorderRadius = 8,
Font = new Font("Bahnschrift", 13),
ForeColor = Color.White,
FillColor = ColorTranslator.FromHtml("#1E1E1E"),
BorderColor = ColorTranslator.FromHtml("#2C2C2C"),
Location = new Point(450,top)
};
MessageBox.Show(i.ToString());
top = h_p;
flowLayoutPanel1.Controls.Add(new_note);
curr = 0;
}
}
uj5u.com熱心網友回復:
問題是由于您設定的回圈內部總是curr回到零。并且根本不需要回圈,因為您想在每次單擊時添加一個文本框。因此,您只需要查看 FlowLayoutPanel 的 Count 屬性并使用該值來準備名稱。
另一個要解決的問題是如何在面板內定位下一個控制元件,但您可以再次使用 Count 屬性輕松計算
private void guna2Button1_Click(object sender, EventArgs e)
{
int nextTop = 25 (flowLayoutPanel.Controls.Count * 170);
var new_note = new Guna2TextBox() {
Text = "Title\n",
Name = "Note" flowLayoutPanel.Controls.Count 1,
.....
Location = new Point(450,nextTop)
};
flowLayoutPanel1.Controls.Add(new_note);
}
uj5u.com熱心網友回復:
在這種情況下,我認為您不需要使用For回圈。您可以只curr為每個文本框使用該變數。For因此,您可以使用以下命令代替回圈:
int top = 25;
int h_p = 170;
curr ;
var new_note = new Guna2TextBox() {
Text = "Title\n",
Name = "Note" curr,
Multiline = true,
AcceptsTab = true,
AcceptsReturn = true,
WordWrap = false,
ScrollBars = ScrollBars.Vertical,
Width = 220,
Height = 110,
BorderRadius = 8,
Font = new Font("Bahnschrift", 13),
ForeColor = Color.White,
FillColor = ColorTranslator.FromHtml("#1E1E1E"),
BorderColor = ColorTranslator.FromHtml("#2C2C2C"),
Location = new Point(450,top)
top = h_p;
flowLayoutPanel1.Controls.Add(new_note);
};
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/506816.html
