2

Firstly, I am most comfortable coding in Java. I am creating an application in C# as a learning tool. In this app I am calling a method from a Click Event Method.

    private void btnViewFile_Click(object sender, EventArgs e) {
        GetFileNames();
        lblOutputPath.Text = sb;
    }

    private StringBuilder GetFileNames() {
        StringBuilder sb = new StringBuilder();
        string[] fileNames = Directory.GetFiles(Dir);
        foreach (string s in fileNames)
            sb.Append(s);

        return sb;
    }

I want to break out the code that gets the FileNames of each file in the directory out of the Click method to keep it more modularized. I would get a value for the StringBuilder object and then pass it back into the Click event method.

That's how I would do it in Java at any rate. Is this an effective tack or is there a better way to do this?

2 Answers 2

5

I think this is what you're trying to do:

private void btnViewFile_Click(object sender, EventArgs e) 
{               
    lblOutputPath.Text = GetFileNames().ToString();    
}    

private StringBuilder GetFileNames() 
{        
    StringBuilder sb = new StringBuilder();        
    string[] fileNames = Directory.GetFiles(Dir);        
    foreach (string s in fileNames)            
        sb.Append(s);        
    return sb;    
}
Sign up to request clarification or add additional context in comments.

Comments

2

Your GetFileNames() method is already returning a value that you are ignoring so you should just assign the returned value from GetFileNames() to label's text property.

Edit: After re-reading your question I am a little confused. Do you want to assign the value of your GetFileNames() to the button's click event before it is actually clicked or use the result when it is clicked? You could assign the value to the button before a click by using the following:

btnViewFiles.CommandArgument = GetFileNames().ToString();

Then when your button is clicked you can read the CommandArgument with the following:

Button btn = (Button)(sender);
lblOutputPath.Text = btn.CommandArgument;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.