What is the easy way to set all empty string textbox ("") to null value in Csharp winform?
Solution 1
You can iterate through the ControlCollection of the given form, e.g. frmMain.Controls
Now this will be the basic Control object, so you would need a test to see if it is of type TextBox.
.NET 2.0 - you'll have to check this manually
.NET 3.0+ - use the .OfType<TextBox>
extension method to give you only a list of IEnumerable<TextBox>
Note that iterating through this from the form will only give you text boxes on that form. If you bind text boxes to a container it won't show up there.
Safest bet would be to write a recursive function that walks through all the control collections and passes the reference to your test function to perform your test and update.
Solution 2
Simple way is Loop through every control, see the below code
foreach (Control C in this.Controls)
{
if (C is TextBox)
{
if (C.Text == "")
{
C.Text = null;
}
}
}
Solution 3
It is one more way
foreach(Control txt in this.Controls)
{
if(txt.GetType() == typeof(TextBox))
if(string.IsNullOrEmpty(txt.Text))
txt.Text = null;
}
Hope it helps
Solution 4
Try this:
foreach(Control c in this.Controls)
{
if (c.GetType().FullName == "System.Windows.Forms.TextBox")
{
TextBox t = (TextBox)c;
t.Clear();
}
}
JatSing
Updated on August 01, 2022Comments
-
JatSing over 1 year
Suppose I don't want to use
if (string.IsNullOrEmpty(textbox1.Text)) { textbox1.Text = null; }
for every textbox controls in form, is there a easier way to do it ?