1

How can I get the text from a dynamicly created RichTextBox and a dynamicly created rtb_TextChanged Event?

e.g:

    private void button1_Click(object sender, EventArgs e)
    {
        RichTextBox rtb = new RichTextBox();
        rtb.Name = "rtb" + i;
        rtb.Dock = DockStyle.Fill;

        rtb.TextChanged += rtb_TextChanged;

        Controls.Add(rtb);

    }

    void rtb_TextChanged(object sender, EventArgs e)
    {
        //string s = rtb.Text;    //How can I get the rtb.Text?
    }

3 Answers3

3

You need to use the sender argument of your event handler:

void rtb_TextChanged(object sender, EventArgs e)
{
    RichTextBox rtb = (RichTextBox)sender;
    string s = rtb.Text;
    //... etc
}
RoadieRich
  • 6,330
  • 3
  • 35
  • 52
2

You just need to use the event parameter : sender

private void richTextBox1_TextChanged(object sender, EventArgs e)
{  
       RichTextBox rtb = (RichTextBox)sender;
       var str = rtb .Text;
}
MRebai
  • 5,344
  • 3
  • 33
  • 52
0

First rtb is not the name that you called the textbox. Since the textbox sent the message you could cast the sender to a textbox and look at its text property.

jfin3204
  • 699
  • 6
  • 18