Search code examples
c#textboxfile-import

C# Text Box File Import


I've got a form with multiple text boxes which are file paths for the program to import data from. Currently they are checked for non-zero length by the following:

    //this code imports the files required by the user, as specified in the
    //file path text boxes
    private void btImport_Click(object sender, EventArgs e)
    {
        bool hasPath = false;
        foreach (TextBox box in this.gbPaths.Controls.OfType<TextBox>().Where(tb => tb.Text.Length > 0))
        {
            hasPath = true;
            //import code
        }//end foreach

        if (!hasPath)
        {
            MessageBox.Show("You must enter at least one file path.");
        }//end if
    }//end import code

What I'm wondering is can I replace the //import code part with something like:

if(tb.Name = "txtAvF") then...

or similar, or do I have to do it outside of the foreach loop? Thanks in advance. Let me know if I need to clarify anything.


Solution

  • If you want to check to see if the TextBox is one of the ones on the form (which I think you are), then you are == which (taken from MSDN)

    the operator == tests for reference equality by determining if two references indicate the same object

    So this is what you're looking for:

    if(box == textBox1 && !string.IsNullOrEmpty(box.Text))
    {
          // Import Textbox1
    }
    else if(box == textBox2 && !string.IsNullOrEmpty(box.Text))
    {
          // Import Textbox2
    }
    else if (box == textBox3....)