My goal is to change tab's title to the one in the text field, when user enters it. Well, problem is, text form is dynamically created within a procedure, and thus inaccessible from other procedures. I made an event handler, but to my surprise, EventArgs held none of the text field's properties. Code's the following:
private void toolStripButton1_Click(object sender, EventArgs e)
{
NewChar();
}
private void NewChar()
{
TabPage ntab = new TabPage("New char");
TextBox cname 开发者_运维知识库= new TextBox();
tabControl1.Controls.Add(ntab);
ntab.Controls.Add(cname);
cname.Location = new Point(10, 10);
cname.TextChanged += new EventHandler(cname_TextChanged);
}
Finally, I managed to notice, that event's sender value holds text field's current text, so I simply cut this value from sender's string reperesentation:
void cname_TextChanged(object sender, EventArgs e)
{
string tmp = sender.ToString();
int pos = tmp.IndexOf(":");
string txt = tmp.Substring(pos+1);
tabControl1.SelectedTab.Text = txt;
}
Although this works fine, I feel that there's got to be a more gentle way to do this. If you happen to know one, could you please enlighten me?
Thanks for your time.
Rather than parse out the results of the ToString() you can just cast it to a textbox and then access the Text Directly
void cname_TextChanged(object sender, EventArgs e)
{
TextBox txt= sender as TextBox;
if (txt !=null)
tabControl1.SelectedTab.Text = txt.Text;
}
精彩评论