开发者

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.


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....)


You should do it inside of the loop. Like this:

if (box.Name == "txtAvF")
    box.Text = "What you want";

But setting hasPath inside the loop just holds state for your last path. You should also move MessageBox code inside loop.


The hasPath assignment seems correct to me; it's set for any one text box, and if not set at the end of the loop, a message is displayed. This rhymes well with the text so displayed. Moving the MessageBox call into the loop would cause the dialog box to never be displayed (or errenously displayed), at least as the code is implemented now, since the OfType<>().Where() guarantees that all text boxes iterated over have at least some content.

(I would add this as a comment to @Xaqron but don't have the necessary reputation yet.)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜