Refreshing Forms in C#
I have a form with multiple textbox and combox .When I click save & new button , I want to clear all textbox and set selectedIndex to 0 combobox. I don't want to use like this txtAddress =开发者_高级运维 "" . Please help me!
Check this: http://www.hariscusto.com/programming/reset-all-controls-on-forms/
But you can't always follow this, because sometime your forms has binding from database like combobox binding or gridview binding with the updated material. So you must create a function yourself, from where you set you textbox empty and rebind the binding controls from database.
Do you want to do like this ↓
var lstTextbox = from p in controls
where p is System.Windows.Forms.TextBox
select p as System.Windows.Forms.TextBox;
foreach (var txt in lstTextbox)
txt.Clear();
On the onClientClick event of the button, call a javascript function ResetAll() where you can reset the values of the controls. Simplest and fast.
What you can do is add all the text boxes in to an Array and then loop through the array and set the .text
property to "" for each one. You will need to the same for your combo boxes as well.
There is unfortunately no magic ClearAllMyTextboxesAndResetMyComboBoxes()
method.
- IF you have a databinging for controls on the Form, just clear the data binded to that controls
If not, I'm affraid you have to assign empty string to TextBox, like you said. May be you can create an iteration over controls.
foreach(Control ctrl in this.Controls) { if(ctrl is TextBox) ((TextBox)ctrl).Text = string.Empty; else if(ctrl is SoemthigElse) //do somethign else for other control }
private List<Binding> bindingCollection = new List<Binding>();
private void ClearCurrentDatabindings()
{
if (bindingCollection.Count > 0)
{
foreach (Binding binding in bindingCollection)
{
binding.Control.DataBindings.Clear();
}
bindingCollection.Clear();
}
}
private void BindTextBox(object target, string targetProperty,
Control controlToBind )
{
Binding binding = new Binding("Text", target, property);
control.DataBindings.Add(binding);
bindingCollection.Add(binding);
}
On adding your databindings you do this:
BindTextBox(customer, "Name" txt_CustomerName);
When you want to clear all:
ClearCurrentDatabindings()
If you're not databinding like this (and I see on reason not to do it) then you must do it manually, or create similar methods like SetTextboxText(txt_Name, "some text")
which will register all your controls to a collection you can clear later.
精彩评论