尝试插入命令时在数据源中收到错误

时间:2018-10-19 18:43:54

标签: c# asp.net sql-server datasource

尝试数据源的InsertCommand时收到以下错误消息:

过程或函数'student_insert'需要未提供的参数'@password'。

除了“ password”外,我在ASCX页面中设置了大多数参数,因为在将其保存到数据库之前,我需要对其进行一些操作:

<InsertParameters>
        <asp:Parameter Name="email" Type="String" />
        <asp:Parameter Name="first_name" Type="String" />
        <asp:Parameter Name="last_name" Type="String" />
        <asp:Parameter Name="university" Type="String" />
        <asp:Parameter Name="program" Type="String" />
        <asp:Parameter Name="student_number" Type="String" />
        <asp:ControlParameter Name="graduation_date" Type="DateTime" ControlID="ctl00$ContentPlaceHolder$ctl01$frmStudents$txtGradDate" PropertyName="Text" />
        <asp:ControlParameter Name="student_card_image_name" Type="String" ControlID="ctl00$ContentPlaceHolder$ctl01$frmStudents$FUStudent" PropertyName="FileName" />
        <asp:ControlParameter Name="id_card_image_name" Type="String" ControlID="ctl00$ContentPlaceHolder$ctl01$frmStudents$FUID" PropertyName="FileName" />
    </InsertParameters>

C#:

protected void datasource_Inserting(object sender, SqlDataSourceCommandEventArgs e) {
            ASCIIEncoding encoding = new ASCIIEncoding();
            ControlParameter cp = new ControlParameter("@password", DbType.Binary, "ctl00$ContentPlaceHolder$ctl01$frmStudents$txtPassword", "Text");
            FormView frmStudents = (FormView)FindControl("frmStudents");
            TextBox txtPassword = (TextBox)(frmStudents.FindControl("txtPassword"));

            datasource.InsertParameters.Add("password", DbType.Binary, encoding.GetBytes(Cryptogrpahy.Encrypt(txtPassword.Text, basepage.crypt_password)).ToString());
        }

当我在调试器中浏览该方法时,我看到了我的整个InsertParameters,带有值...

Screenshot of debugger

另外,请注意,由于数据库类型的原因,我不确定这是否会成功执行,因为我通常在常规SQLParamater中使用VarBinary。

1 个答案:

答案 0 :(得分:0)

我找不到关于它的文档,但是我怀疑发生了什么事,就是在执行事件处理程序代码之前,在Insert事件期间创建的SqlCommand对象正在从SqlDataSource.InsertParameters对象的状态获取其参数。您正在将参数添加到SqlDataSource中,但是由于创建了SqlCommand并在将参数添加到SqlDataSource实例之前从SqlDataSource实例接收了其参数,因此SqlCommand永远不会获得密码参数。

要解决此问题,请尝试将密码参数添加到事件处理程序中的e.Command.Parameters而不是datasource中。

protected void datasource_Inserting(object sender, SqlDataSourceCommandEventArgs e) {
            ASCIIEncoding encoding = new ASCIIEncoding();
            ControlParameter cp = new ControlParameter("@password", DbType.Binary, "ctl00$ContentPlaceHolder$ctl01$frmStudents$txtPassword", "Text");
            FormView frmStudents = (FormView)FindControl("frmStudents");
            TextBox txtPassword = (TextBox)(frmStudents.FindControl("txtPassword"));

            e.Command.Parameters.Add("password", DbType.Binary, encoding.GetBytes(Cryptogrpahy.Encrypt(txtPassword.Text, basepage.crypt_password)).ToString());
        }