NOSDUH
NOSDUH

Reputation: 111

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. 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.

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. 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. 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:

<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> 

Upvotes: 2

Views: 2188

Answers (2)

Vivek S.
Vivek S.

Reputation: 21915

You can use Val()

Val() - Returns the numbers contained in a string as a numeric value of appropriate type.

 Dim id As Integer = val(lblSubmissionID.Text)

and imo, Dim SubmissionID As String = lblSubmissionID.Text is not needed


I suspect the real problem is with your query plan, i.e

insert into submissions(selected) ('Yes') WHERE submissionid=1 is not a valid insert statement you need to use UPDATE here

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

Upvotes: 0

Creator
Creator

Reputation: 1512

Convert.ToInt16(idrow.Cells(0).Text) Will convert the cell to int

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

or

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

if Id is already an integer

Upvotes: 0

Related Questions