pave
pave

Reputation: 358

Passing Args from Method to Click Event Method in C#

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?

Upvotes: 2

Views: 347

Answers (2)

Kelsey
Kelsey

Reputation: 47726

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;

Upvotes: 2

user27414
user27414

Reputation:

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;    
}

Upvotes: 5

Related Questions