public void yeni()
{
//....
RichTextBox rtb = new RichTextBox();
rtb.Name = "richTextBox" + selectedTabPageIndex.ToString();
rtb.TextChanged += rtb_TextChanged;
//....
}
void rtb_TextChanged(object sender, EventArgs e)
{
RichTextBox rtb = (RichTextBox)sender;
if (rtb.Name == "richTextBox" + selectedTabPageIndex.ToString())
{
//rtb is selected page richtextbox
//......
}
}
TextChanged event for dynamically created RichTextBoxes
-
09-03-2022 - |
Question
I'm trying to do a notepad with chrome-like tabs on it. I have a "New Page" button on my page. When I click on it, it creates a new tabpage with a richtexbox on it. The richboxes are created like this
public void yeni()
{
//create a new tabpage
TabPage newPage = new TabPage("Not-" + (tabControl1.TabPages.Count + 1));
//create a new richtexbox
RichTextBox rtb = new RichTextBox();
int rtbname = tabControl1.TabPages.Count + 1;
rtb.Name = "richTextBox" + rtbname.ToString();
rtb.Anchor = (AnchorStyles.Bottom | AnchorStyles.Right | AnchorStyles.Left | AnchorStyles.Top);
rtb.BorderStyle = BorderStyle.None;
rtb.Width = 778;
rtb.Height = 395;
rtb.Location = new Point(0, 4);
rtb.HideSelection = false;
rtb.Font = new Font("Lucida Console", 9.75f);
rtb.ForeColor = Color.Maroon;
//add rtb to the tabpage
newPage.Controls.Add(rtb);
tabControl1.TabPages.Add(newPage);
//make the new created tab the selected one
tabControl1.SelectedTab = tabControl1.TabPages[tabControl1.TabPages.Count - 1];
//selectedRtb.Text = null;
openFileDialog1.FileName = null;
}
Now I create a RichTextBox and the name of that rtb is richTextBox*indexofthetabhere*. So if I'm working on the second tabpage, the name of the rtb is "richTextBox2". Now what I'm trying to do is I want an textchanged event for the richtextbox on the selected tabpage. I'm getting the selected richtextbox with this code here.
private void tabControl1_SelectedIndexChanged(object sender, EventArgs e)
{
selectedone = "richTextBox" + (tabControl1.SelectedIndex+1).ToString();
selectedRtb = (RichTextBox)tabControl1.SelectedTab.Controls[selectedone];
textBox2.Text = selectedone;
}
Now here I get the selected tab index and i get the rtb name then I get the selected rtb as "selectedRtb". Now I can't make a textchanged event for this. I don't know what to do actually. I tested if the above code was working and yes I get the rtb names right. But I can't use them because I don't know how to do.. Thanks for the help.
La solution
Autres conseils
You don't know how to create events? Or you can't access something while knowing it's name (use reflection)?
Alright I solved my problem. Here is the answer;
selectedRtb.TextChanged += (bs, be) =>
{
//whatever you want to do
};
Simply added this to my code after I created the rtb, and it worked. Thanks to everyone who helped.