【发布时间】:2014-02-12 19:50:12
【问题描述】:
我正在开发一个软件,我想在完成特定任务后清除每一件事,比如清除所有字段、列表视图等,我要写很多要清除的东西,就像我的新按钮的代码是:
private void btnNew_Click(object sender, EventArgs e)
{
txtProductCode1.ReadOnly = false;
txtInvoiceNo.ReadOnly = false;
cmbCustoemerType.Enabled = false;
cmbCustomerName.Enabled = false;
button1.Enabled = true;
txtProductCode1.Text = null;
txtWageName.Text = null;
txtWageCost.Text = null;
btnFirst.Visible = false;
btnPrevious.Visible = false;
btnNext.Visible = false;
btnLast.Visible = false;
cmbProductName.Enabled = true;
txtQty.ReadOnly = false;
txtPercant.ReadOnly = false;
txtDiscount.ReadOnly = false;
cmbCustoemerType.Enabled = true;
cmbCustomerName.Enabled = true;
button5.Enabled = true;
btnDelete.Enabled = true;
dtp1.Enabled = true;
btnSave.Text = "&Save";
cmbCustoemerType.Text = null;
cmbCustomerName.Text = null;
txtInvoiceNo.Clear();
txtDiscount.Clear();
txtGrandTotal.Clear();
txtProductName.Clear();
txtSalePrice.Clear();
txtQty.Clear();
txtTotal.Clear();
txtExtraWages.Text = null;
lvExtraWages.Items.Clear();
lvTransaction.Items.Clear();
lblCount.Text = null;
lblNetTotal.Text = null;
txtPercant.Text = null;
txtInvoiceNo.Text = invoice.ToString();
}
有什么办法可以摆脱再次编写代码的麻烦,就像我需要在另一个按钮上启用我在此处禁用的一件事,所以我必须编写反向代码来完成任务,这真的是恼人的!有没有其他方法可以做到这一点?
编辑:
尝试了以下代码:
private void btnNew_Click(object sender, EventArgs e)
{
//using setboxdefault function
SetTextBoxDefaults();
cmbCustoemerType.Text = null;
cmbCustomerName.Text = null;
cmbCustoemerType.Enabled = false;
cmbCustomerName.Enabled = false;
cmbProductName.Enabled = true;
cmbCustoemerType.Enabled = true;
cmbCustomerName.Enabled = true;
button5.Enabled = true;
btnDelete.Enabled = true;
button1.Enabled = true;
btnFirst.Visible = false;
btnPrevious.Visible = false;
btnNext.Visible = false;
btnLast.Visible = false;
btnSave.Text = "&Save";
lvExtraWages.Items.Clear();
lvTransaction.Items.Clear();
lblCount.Text = null;
lblNetTotal.Text = null;
dtp1.Enabled = true;
txtInvoiceNo.Text = invoice.ToString();
}
private void SetTextBoxDefaults()
{
var textBoxes = GetControls(this, typeof(TextBox));
foreach (var textBox in textBoxes)
{
TextBox.Clear();
}
}
public IEnumerable<Control> GetControls(Control control, Type type)
{
var controls = control.Controls.Cast<Control>();
return controls.SelectMany(ctrl => GetControls(ctrl, type)).Concat(controls).Where(c => c.GetType() == type);
}
但它在 TextBox.Clear(); 上给出错误,错误是错误 4
An object reference is required for the non-static field, method, or property 'System.Windows.Forms.TextBoxBase.Clear()'
请让我知道我在哪里弄错了..!!
【问题讨论】:
-
你试过循环遍历控件集合吗?
-
@Tim 不,遗憾的是我不知道
-
这可能就是你要找的东西:stackoverflow.com/questions/15569641/…
-
看他怎么不知道自己在做什么,应该是winforms吧。
-
是的,但如果是 1500 行的属性分配,那么之后你可能会远远少于一半。