使用SqlDataSource调用带参数存储过程插入数据

最近被朋友问到一个SqlDataSource调用带参数存储过程为什么不成功,代码如下:

ContractedBlock.gif ExpandedBlockStart.gif 代码
 
   
string user_name = ((TextBox) this .DetailsView1.Rows[ 1 ].Cells[ 1 ].Controls[ 0 ]).Text.ToString().Trim();

string pass_word = ((TextBox) this .DetailsView1.Rows[ 2 ].Cells[ 1 ].Controls[ 0 ]).Text.ToString().Trim();
SqlDataSource1.InsertCommand
= " pro_newUser " ;
SqlDataSource1.InsertCommandType
= SqlDataSourceCommandType.StoredProcedure;

SqlDataSource1.InsertParameters.Add(
" x " , TypeCode.String, user_name);
SqlDataSource1.InsertParameters.Add(
" y " , TypeCode.String, pass_word);

SqlDataSource1.Insert()

        是啊,为什么不成功呢,提示的消息是太多的参数,这段代码看起来没什么问题啊。几轮搜索以后,觉得网上说的种种原因,最可能的是参数名要和字段名一致和参数要加@于是改成:

 

string user_name = ((TextBox)this.DetailsView1.Rows[1].Cells[1].Controls[0]).Text.ToString().Trim();  
 
string pass_word = ((TextBox)this.DetailsView1.Rows[2].Cells[1].Controls[0]).Text.ToString().Trim();  
SqlDataSource1.InsertCommand = "pro_newUser";  
SqlDataSource1.InsertCommandType = SqlDataSourceCommandType.StoredProcedure;  
 
SqlDataSource1.InsertParameters.Add("@empNo", TypeCode.String, user_name);  
SqlDataSource1.InsertParameters.Add("@empName", TypeCode.String, pass_word);  
 
SqlDataSource1.Insert()

存储过程里也进行相应的修改,把定义的传入参数和调用的地方都改为@empNo,@empName,仍然失败!错误消息变成了

Procedure or Function 'asdfg' expects parameter '@empNo', which was not supplied.就是没找到@empNo,此时,我有点迷茫。

于是把@去掉,再试,成功。代码如下:

 

ContractedBlock.gifExpandedBlockStart.gif代码
 
    

string user_name = ((TextBox)this.DetailsView1.Rows[1].Cells[1].Controls[0]).Text.ToString().Trim();

        string pass_word = ((TextBox)this.DetailsView1.Rows[2].Cells[1].Controls[0]).Text.ToString().Trim();
        SqlDataSource1.InsertCommand = "pro_newUser";
        SqlDataSource1.InsertCommandType = SqlDataSourceCommandType.StoredProcedure;

        SqlDataSource1.InsertParameters.Add("empNo", TypeCode.String, user_name);
        SqlDataSource1.InsertParameters.Add("empName", TypeCode.String, pass_word);

        SqlDataSource1.Insert()



 

但是会产生两条数据,这段代码是写在DetailsView1_ItemInserting里的,根据以前的经验,这个方法在点DetailsView1的插入按钮时触发,只要InsertCommand中有代码,就会去执行,那么最后的一句SqlDataSource1.Insert()具有相同的作用,所以等于把insertCommand执行了两次,所以会有两条数据。

很奇怪,我一直觉得我遇到的问题别人也一定会遇到过,但是这个例外,尝试了各种搜索条件,没有这个问题。所有的文章都说调用存储过程传参要用@占位符。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值