简体   繁体   English

在插入数据库ASP.NET VB.NET之前将文本框字符串转换为Integer

[英]Converting textbox string to Integer prior to inserting into database ASP.NET VB.NET

I have a web page that displays several different grid views and detail views on the page. 我有一个网页,该网页在页面上显示几个不同的网格视图和详细信息视图。 I am using a select column in my grid view to take a specific cell value and feed it to an asp label. 我在网格视图中使用选择列,以获取特定的单元格值并将其提供给asp标签。 I am trying to take the value from the label and use it in my sql query which inserts 'yes' into the database based on which value is fed to the label but I keep getting am incorrect syntax error when executing the query. 我正在尝试从标签中获取值,并在我的sql查询中使用它,该查询会根据馈给标签的值将'yes'插入数据库,但是在执行查询时,我总是收到不正确的语法错误。

To give you more context, I have two types of users, student and business. 为了给您更多的背景信息,我有两种类型的用户,学生和企业。 The grid view displays submission information from a student user that a business user can then select as a winning submission. 网格视图显示来自学生用户的提交信息,企业用户随后可以选择该信息作为获奖提交。 The column I am feeding into the asp label is the submission id number (PK), which is an int in the database. 我要输入到asp标签的列是提交ID号(PK),它是数据库中的int。 Based on the submission id, the business user can then choose to flag the selected submission as a winning submission by clicking on an asp button which kicks off my sql command to insert into the database. 然后,基于提交ID,业务用户可以通过单击asp按钮(将我的sql命令插入到数据库中)启动一个asp按钮,以将所选提交标记为获胜提交。 I am not sure what conversion method to use to accomplish this task. 我不确定要使用哪种转换方法来完成此任务。

Here is my code behind: 这是我的代码背后:

Imports System.Data

Partial Class InteriorBusinessProjectDetails
    Inherits System.Web.UI.Page
    Dim conn As New Data.SqlClient.SqlConnection("DatabaseConnetionString")

    Sub GridView1_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs)
        ' Get the currently selected row using the SelectedRow property.
        Dim row As GridViewRow = GridView1.SelectedRow

        lblSelectSubmission.Visible = True
        lblSubmission.Visible = True
        lblSubmissionID.Visible = True
        btnSelect.Visible = True
        btnCancel.Visible = True

        lblSubmissionID.Text = row.Cells(0).Text
    End Sub

    Protected Sub btnSelect_Click(sender As Object, e As EventArgs) Handles btnSelect.Click

        Dim SubmissionID As String = lblSubmissionID.Text
        Dim id As Integer = Convert.ToInt32(Convert.ToDecimal(SubmissionID))

        conn.Open()

        Dim cmd As New Data.SqlClient.SqlCommand(("INSERT INTO Submissions (Selected) VALUES ('Yes') WHERE SubmissionID=@SubmissionID"), conn)
        cmd.Parameters.Add("@SubmissionID", SqlDbType.Int).Value = id
        cmd.ExecuteNonQuery()

        conn.Close()

        lblSubmission.Visible = False
        lblSubmissionID.Visible = False
        btnSelect.Visible = False
        btnCancel.Visible = False
        lblSelectSubmission.Visible = True
        lblSelectSubmission.Text = "You have successfully chosen a submission for your project!"

    End Sub
End Class

The exception is thrown here: 这里抛出异常:

cmd.Parameters.Add("@SubmissionID", SqlDbType.Int).Value = id
cmd.ExecuteNonQuery()

Here is the stack trace: 这是堆栈跟踪:

StackTrace:
       at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
       at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
       at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
       at System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)
       at System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString)
       at System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async, Int32 timeout, Task& task, Boolean asyncWrite, SqlDataReader ds, Boolean describeParameterEncryptionRequest)
       at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, TaskCompletionSource`1 completion, Int32 timeout, Task& task, Boolean asyncWrite)
       at System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(TaskCompletionSource`1 completion, String methodName, Boolean sendToPipe, Int32 timeout, Boolean asyncWrite)
       at System.Data.SqlClient.SqlCommand.ExecuteNonQuery()
       at InteriorBusinessProjectDetails.btnSelect_Click(Object sender, EventArgs e) in C:\Users\richard\Desktop\BRAINbait PLATINUM 11.24.15\InteriorBusinessProjectDetails.aspx.vb:line 32
       at System.Web.UI.WebControls.Button.OnClick(EventArgs e)
       at System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument)
       at System.Web.UI.WebControls.Button.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument)
       at System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument)
       at System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData)
       at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)

And the GUI on the front end with the label in which I am pulling the value from, along with the button that initiates my Click event: 前端的GUI带有我从中提取值的标签,以及引发Click事件的按钮:

<h2 style="margin-left:auto; margin-right:auto; text-align:center; color:#FF9933;"><asp:Label ID="lblSelectSubmission" runat="server" Text="Would you like to choose the following submission for your project?" Visible="false"></asp:Label></h2>
        <h2 style="margin-left:auto; margin-right:auto; text-align:center; color:#FF9933;"><asp:Label ID="lblSubmission" runat="server" Text="Submission Number: " Visible="false"></asp:Label><asp:Label ID="lblSubmissionID" runat="server" Text="" Visible="false"></asp:Label></h2>
        <center><asp:Button ID="btnSelect" runat="server" Text="Select" CssClass="submit" TabIndex="0" Visible="false" /><asp:Button ID="btnCancel" runat="server" Text="Cancel" CssClass="submit" TabIndex="1" Visible="false" /></center> 

Convert.ToInt16(idrow.Cells(0).Text) Will convert the cell to int Convert.ToInt16(idrow.Cells(0).Text)将单元格转换为int

cmd.Parameters.Add("@SubmissionID", Convert.ToInt16(idrow.Cells(0).Text))

or 要么

cmd.Parameters.Add("@SubmissionID", Id))

if Id is already an integer 如果id已经是一个整数

You can use Val() 您可以使用Val()

Val() - Returns the numbers contained in a string as a numeric value of appropriate type. Val() -以适当类型的数值返回字符串中包含的数字。

 Dim id As Integer = val(lblSubmissionID.Text)

and imo, Dim SubmissionID As String = lblSubmissionID.Text is not needed 和imo, Dim SubmissionID As String = lblSubmissionID.Text 不需要


I suspect the real problem is with your query plan, ie 我怀疑真正的问题在于您的查询计划,即

insert into submissions(selected) ('Yes') WHERE submissionid=1 is not a valid insert statement you need to use UPDATE here insert into submissions(selected) ('Yes') WHERE submissionid=1不是有效的插入语句,您需要在此处使用UPDATE

Protected Sub btnSelect_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnSelect.Click
        Dim id As Integer = Val(lblSubmissionID.Text)
        conn.Open()
        Dim cmd As New Data.SqlClient.SqlCommand(("update Submissions  set Selected='Yes' WHERE SubmissionID=@SubmissionID"), conn)
        cmd.Parameters.Add("@SubmissionID", SqlDbType.Int).Value = id
        cmd.ExecuteNonQuery()
        conn.Close()
        lblSubmission.Visible = False
        lblSubmissionID.Visible = False
        btnSelect.Visible = False
        btnCancel.Visible = False
        lblSelectSubmission.Visible = True
        lblSelectSubmission.Text = "You have successfully chosen a submission for your project!"
    End Sub

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM