Sunday, February 19, 2012

How to use a variable in a SQL statement…

Hi,

background

From a 'members' table, I get the first letter of the last name of the members and display in a dataList as buttons.

In the dataList control, the

<asp:button>
has the following:
CommandArgument='<%# DataBinder.Eval(...) %>' OnCommand="doSomething"

In the code behind page I have the following code:


Public Sub doSomething(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.CommandEventArgs)
Dim getLastName as string = e.CommandArgument.ToString()
lblBtn.Text = "clicked " + e.CommandArgument.ToString()


This code will do the job – in the label 'lblBtn' the text will show the 'value' that the button represents – i.e. if you click the button for 'B' the lblBtn will read 'clicked B'

The problem

Now that I know which button was clicked, I need to use the information in a SQL query to retrieve the relevant data.


Const strSQL2 As String = "select * from members where letter = 'getLastName'"

This query returns no records at all – no errors, just nothing. What I am doing wrong?

Kindly help.

Thanks,

Sami.a couple of questions:
1> Is the first letter of the last name stored in Members under field letter?
2> Is the following statement used in doSomething?


Const strSQL2 As String = "select * from members where letter = 'getLastName'"

If the answer to both questions are YES. Here is your correct strSQL2:


Const strSQL2 As String = "select * from members where letter = '" & getLastName & "'"
|||Thanks for your response – yes, you are right on both assumptions. I did what you suggested but got an error.

In VS the expression 'getLastName' got a blue underline and when I mouse over it I get a balloon message that says 'Constant expression is required'

When I 'view in browser' and click 'yes' for continuing with the preview and then click on one of the letter buttons I get an error page with the following message:

Incorrect syntax near '='

Any suggestions?

Thanks for your patience - I am very new at this

Sami.|||Sorry. My fault. Overlooked your statement. Please remove "Const " from your statement below.


Const strSQL2 As String = "select * from members where letter = 'getLastName'"


Change to this:


strSQL2 As String = "select * from members where letter = 'getLastName'"

Please let me know if there is still error.|||Wow - thank you so much...

It works great.

Sami.

No comments:

Post a Comment