You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C# WinForm向DataSet插入数据后弹MessageBox提示的异常咨询

问题根因

代码错误出在两个文本框的TextChanged事件回调逻辑中:直接调用的Text属性默认指向当前AddEmployee窗体的标题属性,而非触发事件的文本框的输入内容,因此存入employeeName、jobTitle的一直是窗体标题「AddEmployee」,最终导致插入DataSet的内容和弹窗输出都异常。

修复方案

方案1:修正TextChanged事件的取值逻辑

将两个TextChanged事件的取值逻辑改为从触发事件的文本框控件取输入值即可:

private void TextBox1_TextChanged(object sender, EventArgs e)
{
    // sender为触发事件的textBox1控件,强转后读取其Text属性
    SetName(((TextBox)sender).Text);
}
private void TextBox2_TextChanged(object sender, EventArgs e)
{
    SetJob(((TextBox)sender).Text);
}

方案2:优化为提交时直接取值(更稳妥)

可以删除不必要的TextChanged事件监听和全局变量,在点击提交按钮时直接读取文本框输入,还可以额外增加空值校验避免无效数据插入:

private void Enter_Click(object sender, EventArgs e)
{
    // 直接读取文本框输入内容
    string employeeName = textBox1.Text.Trim();
    string jobTitle = textBox2.Text.Trim();
    
    // 非空校验逻辑,可按需保留
    if(string.IsNullOrEmpty(employeeName) || string.IsNullOrEmpty(jobTitle))
    {
        MessageBox.Show("员工姓名和职位不能为空");
        return;
    }
    
    string newEmployee = $"{employeeName} has been added to the employee directory with the title of {jobTitle}";
    EmployeeDirectoryDataSetTableAdapters.EmployeeDirectoryTableAdapter EmployeeDirectoryTableAdapter =
    new EmployeeDirectoryDataSetTableAdapters.EmployeeDirectoryTableAdapter();
   
    EmployeeDirectoryTableAdapter.InsertQuery(employeeName, jobTitle);
    textBox1.Text = String.Empty;
    textBox2.Text = String.Empty;
    MessageBox.Show(newEmployee);    
}

内容的提问来源于stack exchange,提问作者RPHennis

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 15:09:03