Passing Args from Click Click Click method in C #

First, I am most comfortable with Java coding. I am creating an application in C # as a learning tool. In this application, I am calling a method from the 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 rip out the code that gets the filenames of each file in a directory from the Click method to make it more modular. I would get the value for the StringBuilder object and then pass it back to the Click event method.

The way I would do it in Java anyway. Is this an efficient approach or is there a better way to do it?

+2


source to share


2 answers


I think this is what you are 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;    
}

      

+5


source


Your method GetFileNames()

already returns a value that you are ignoring, so you should just assign the return value from GetFileNames()

to denote the text property.

Edit: After re-reading your question, I'm a little confused. Do you want to assign the GetFileNames () value to the button click event before actually clicking or using the result when clicked? You can assign a value to a button before clicking using the following:

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

      



Then when you click the button, you can read the CommandArgument with the following:

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

      

+2


source







All Articles