[英]C# Iterating over known textboxes from array
我正在嘗試從string
數組中的string
迭代文本框
static string[] TextBoxes = {
"EmpName",
"Sales",
"BasePay",
"Commission",
"GrossPay",
"Deductions",
"Housing",
"FoodAndClothing",
"Entertainment",
"Misc"
};
以上每個都是表單的一部分,例如 txtHousing 是房屋輸入元素。 等等等等。
迭代發生在這里
private void btnClear_Click(object sender, EventArgs e)
{
for (byte i = 0; i < TextBoxes.Length; i++)
{
this["txt" + TextBoxes[i]].Text = "";
}
this.txtEmpName.Focus();
}
除了這個System.String
出現一個奇怪的“錯誤”之外,我們不能從this
對象中調用this
對象嗎?
只是閱讀一個消息來源說 this.getProperty 可能會起作用,所以我會嘗試這樣做。
錯誤
無法將 [] 索引應用於“Pay_Calculator.PayCalculator”類型的表達式
一種解決方案是使用反射/動態對象。
var me = (dynamic) this;
foreach (var name in TextBoxes)
{
((TextBox) me['txt' + name]).Value = string.Empty;
}
另一種解決方案是遞歸所有控件,然后您不需要命名所有文本框。
private void btnClear_Click(object sender, EventArgs e)
{
ClearTextBox(this);
}
void ClearTextBox (Control c)
{
var t = c as Textbox;
if (t != null)
t.Value = string.Empty;
foreach (var child in c.Controls)
ClearTextBox(child);
}
我認為你需要做這樣的事情
private void btnClear_Click(object sender, EventArgs e)
{
for (byte i = 0; i < TextBoxes.Length; i++)
{
if (this.Controls.ContainsKey("txt" + TextBoxes[i]))
{
TextBox txtBox = this.Controls["txt" + TextBoxes[i]] as TextBox;
if (txtBox != null)
{
// Do your Stuff
txtBox.Text = "";
}
}
}
}
假設WinForms ,將static
更改為private
並使用Controls.Find() :
private string[] TextBoxes = {
"EmpName",
"Sales",
"BasePay",
"Commission",
"GrossPay",
"Deductions",
"Housing",
"FoodAndClothing",
"Entertainment",
"Misc"
};
private void btnClear_Click(object sender, EventArgs e)
{
foreach (string name in TextBoxes)
{
TextBox tb = this.Controls.Find("txt" + name, true).FirstOrDefault() as TextBox;
if (tb != null)
{
tb.Text = "";
}
}
this.txtEmpName.Focus();
}
您必須遍歷控件並檢查控件是否為文本框,稍后您可以檢查控件的名稱以匹配您的數組元素並清除它。
你可以按照這個例子
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.