简体   繁体   English

C# - 文本形式的文本更改事件:有更好的方法吗?

[英]C# - text change event in a text form: is there a better way?

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. 我创建了一个事件处理程序,但令我惊讶的是,EventArgs没有保存任何文本字段的属性。 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 您可以将其转换为文本框,然后直接访问文本,而不是解析ToString()的结果。

void cname_TextChanged(object sender, EventArgs e)
{
    TextBox txt= sender as TextBox;
    if (txt !=null)
          tabControl1.SelectedTab.Text = txt.Text;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM