Load File to RichTextBox

Joined
Jun 3, 2015
Messages
6
Programming Experience
Beginner
This question has been asked and answered many times already, but I have some questions about this that would help if someone can clear things up for me.

This section of code goes in the public class called "button_actions".
C#:
public void button2_Click_Open(object sender, EventArgs e){
    Stream mystream = null;

    OpenFileDialog openfile1 = new OpenFileDialog();

    openfile1.DefaultExt = "*.cpp";
    openfile1.File = "CPP Files|*.cpp";

    //fixed problem with program hanging when "Open" button clicked
    openfile1.AutoUpgradeEnabled = false;

    if(openfile1.ShowDialog() == Dialog.Result.OK){
        try{
            using((mystream = openfile1.OpenFile()) != null){
                richtextbox1.LoadFile(mystream, RichTextBoxStreamType.PlainText);
            }
        }
        catch(Exception ex){
            MessageBox.Show("error:" + ex.Message);
        }
    }
}


And this is nested in the public class "form_layout":
C#:
public button_actions buttonAction = new button_actions();

public void form1_build(Form form1){
    ...
    Button button2 = new Button();
    button2.Click += buttonAction.button2_Click_Open;

    RichTextBox richtextbox1 = new RichTextBox();
...
}

I've seen dozens of threads that demonstrate calling the richtextbox control in the click event function, but this won't work because "richtextbox1" is not available to the "button2_Click_Open" function. Is it possible to pass an additional parameter through this function? When I try "button2.Click += buttonAction.button2_Click_Open(//parameters)" and declare those parameters in the function declaration, it also fails.

I've tried combining this code under the same class and making richtextbox1 public, but it still won't compile. Is it a bad idea to have the open/save actions in a namespace/class separate from the form?

Despite having all classes and members public is there an issue with these being in two separate namespaces?
 
Last edited:
You don't get to choose the signature of an event handler. That is defined by the event itself. Basically, you have designed your code badly. Everything specific to a form should be in that form. If you want a method that will act on any RichTextBox then you can write that method in a common location and add a RichTextBox parameter and then pass a specific RichTextBox in as an argument from the form that it lives on. If you have a handler for the Click event of a Button then it should be in the form that that Button lives on. You can then call methods in other classes from that event handler and pass in whatever is required, which includes controls from that form.
 
Back
Top Bottom