简体   繁体   中英

Check if any textbox has data then do something

A groupbox has several Textbox bounded from database using ExecuteReader now I want to do is if there is only one textbox is not empty then make all Textbox are read only

ExecuteReader return data not like ExecuteNonQuery which returns number of rows retrieved so I cannot get any advantage of it

any other suggestion ?

You can do this with LINQ:

var textBoxes = groupbox.Controls.OfType<TextBox>();

if (textBoxes.Any(tb => !string.IsNullOrEmpty(tb.Text)))
{
    foreach (var t in textBoxes)
    {
        t.ReadOnly = true;
    }
}

Try:

 if (String.IsNullOrEmpty(textBox1.Text))
 {
    // Do something...
 }

Quick and dirty answer: enumerate the controls in the groupbox, test if they are edits, if so check if there is any text in the edits.. like so

foreach (Control c in groupBox1.Controls)
  if (c is TextBox)
    if (((TextBox)c).Text.Length>0)
      {        
        // there is one textbox with text
        // .. do something, like disabling textboxes ..
        break;
      }

You could just loop through your text boxes like this (using Linq):

// Collection of all text boxes
var textBoxes = groupbox.Controls.OfType<TextBox>();
// Check if one text box is not empty
bool hasText = false;
foreach (TextBox tb in textBoxes)
    hasText |= !String.IsNullOrEmpty(tb.Text);
// Set all text boxes to read only
if (hasText)
{
    foreach (TextBox tb in textBoxes) tb.ReadOnly = true;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM