1. 基础控件 Text 操作
- Label / Button / TextBox
- // 设置文本 label1.Text = "用户名:"; button1.Text = "提交"; textBox1.Text = "请输入内容"; // 获取文本 string input = textBox1.Text;
- Form(窗体)
- this.Text = "主窗口"; // 修改窗口标题
- ComboBox(下拉框)
- comboBox1.Text = "默认选项"; // 设置默认显示文本 string selectedText = comboBox1.Text; // 获取用户选择的文本
- CheckBox / RadioButton
- checkBox1.Text = "同意协议"; // 设置选项旁的文字
2. 动态更新 Text
- 定时刷新示例(如时钟):
- private void timer1_Tick(object sender, EventArgs e) { labelTime.Text = DateTime.Now.ToString("HH:mm:ss"); }
- 事件驱动更新(如按钮点击):
- private void btnShow_Click(object sender, EventArgs e) { lblResult.Text = "Hello, " + txtName.Text; }
3. 特殊场景处理
- 跨线程安全更新(非 UI 线程操作控件):
- this.Invoke(() => { labelStatus.Text = "后台任务完成!"; });
- 数据绑定(自动同步数据源):
- // 绑定 TextBox 到对象的 Name 属性 textBox1.DataBindings.Add("Text", myObject, "Name");
- 格式化显示(如数值显示):
- double value = 123.456; lblValue.Text = value.ToString("0.00"); // 显示为 123.46
4. 注意事项
- 空值处理:访问 Text 前建议判空(如 if (!string.IsNullOrEmpty(textBox1.Text)))。
- 密码框:使用 TextBox.PasswordChar 属性隐藏输入(如 textBoxPwd.PasswordChar = '*')。
- 多行文本:设置 TextBox.Multiline = true 以支持换行。
总结:
- Text 是控件内容交互的核心属性,操作需注意线程安全和数据格式。
- 结合数据绑定和事件机制,可高效实现动态界面更新。