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

C# WinForm+Dapper操作SQL报错:TextBox控件无法作为参数值

问题解决:System.NotSupportedException 错误处理

错误原因

你在Dapper的SQL参数中直接传入了TextBox控件对象(textBox1),而非控件的文本值(TextBox.Text属性)。Dapper无法将WinForms控件类型作为SQL参数值,因此抛出该异常。

修正后的代码

将参数中的jdid=textBox1改为jdid=textBox1.Text,确保传入的是文本内容而非控件对象:

namespace faradarss
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        string connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["faradarss"].ToString();

        private void btnsave_Click(object sender, EventArgs e)
        {
            using (var connection = new SqlConnection(connectionString))
            {
                connection.Open();
                // 修正:传入TextBox的Text属性值而非控件对象
                int affectedRow = connection.Execute(
                    "INSERT INTO tblfaradars (id,sen,esm,jdid) VALUES (@id ,@sen ,@esm,@jdid)", 
                    new { id=txtid.Text, sen=txtsen.Text, esm=txtesm.Text, jdid=textBox1.Text });

                if (affectedRow != 0)
                {
                    MessageBox.Show("ردیف ساخت");
                }
                // using块会自动关闭连接,无需手动调用connection.Close()
            }
        }
    }
}

额外优化建议

  • using语句会自动管理数据库连接的生命周期,执行完毕后会自动关闭并释放连接,因此可以删除手动的connection.Close()调用,避免冗余代码。
  • 建议对输入文本做合法性校验(比如非空检查、格式验证),避免无效数据插入数据库。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 14:37:48