如何根据其他2个文本框的输入自动填充文本框?
例如:
名字:约翰
姓氏:史密斯
Alias:JSmit(取得First First,以及姓氏中的前4个字母)
昵称:JSmith(取得第一个首字母,+姓氏)
我如何用C#写这个?它是Visual Studio 2013中的Windows窗体
我认为对于昵称我只能使用txtNickname.text = *有些人很奇怪A ^ @#%@ Thing * + txtLastname.Text;
答案 0 :(得分:0)
txtNickname.Text = txtFirstName.Text[0] + txtLastName.Text;
txtAlias.Text = txtFirstName.Text[0] + txtLastName.Text.Substring(0, 4);
你可能需要为字符串长度添加一些陷阱。 :)
答案 1 :(得分:0)
您正尝试在Windows窗体中实现数据绑定 - 您可以查看this Tutorial。作为替代方案,您可以使用WPF
轻松完成此操作以下是Windows窗体的一些示例WPF样式代码:
public partial class Form1 : Form, INotifyPropertyChanged {
public string FirstName { get { return txtFirstName.Text; } set { txtFirstName.Text = value; } }
public string LastName { get { return txtLastName.Text; } set { txtLastName.Text = value; } }
public string NickName { get { return txtNickName.Text; } set { txtNickName.Text = value; } }
public Form1() {
InitializeComponent();
UpdateNickName();
txtFirstName.TextChanged += (s, e) => FirePropertyChanged("FirstName");
txtLastName.TextChanged += (s, e) => FirePropertyChanged("LastName");
txtNickName.TextChanged += (s, e) => FirePropertyChanged("NickName");
PropertyChanged += Form1_PropertyChanged;
}
void Form1_PropertyChanged(object sender, PropertyChangedEventArgs e) {
switch(e.PropertyName) {
case "FirstName":
case "LastName":
UpdateNickName();
break;
}
}
void UpdateNickName() {
if(FirstName.Length > 1 && LastName.Length > 4) {
NickName = FirstName.Substring(0, 1) + "" + LastName.Substring(0, 4);
} else {
NickName = "";
}
}
public void FirePropertyChanged([CallerMemberName] string property = "") {
if(PropertyChanged != null) {
PropertyChanged(this, new PropertyChangedEventArgs(property));
}
}
public event PropertyChangedEventHandler PropertyChanged;
}