Filling a String variable with a single entry from a database

J

Jim in Arizona

Is there an easy way to just get a single value from a database and put
it into a string?

This is as far as I can get:

Dim TKEY As String
TKEY = dlShowRequests.DataKeys(e.Item.ItemIndex)

Dim strConnection, strSQL, strADName As String
strConnection = ConfigurationManager.AppSettings("maintenance")
strSQL = "SELECT empname FROM TWorkRequest WHERE ID = " & TKEY

Dim objConnection As New SqlConnection(strConnection)
Dim objCommand As New SqlCommand(strSQL, objConnection)

objConnection.Open()
objCommand.ExecuteReader()
objConnection.Close()

Normally, I could use a control, like a gridview, and use the datasource
then databind property/method to get the data. But, how could I simply
just put the single value, which my SQL string would produce, into a
single string variable?

I thought about just making a label or textbox object and binding it to
that but they don't have datasource properties.
 
T

ThunderMusic

Hi,

First of all, for just a single value like this, I'd go with
objCommand.ExecuteScalar() (instead of ExecuteReader()) and just cast the
result to string like this :

string yourVar = objCommand.ExecuteScalar().ToString();

One thing to not tought, if your command returns a DBNull you will have an
exception, so the best way to go if you don't know for sure there will be a
result is like this :

object obj = objCommand.ExecuteScalar();
string yourVar = (obj == DBNull.Value) ? string.Empty : obj.ToString();

you can also put null instead of string.Empty because string is a nullable
type, it's your choice... ;)

I hope it helps

ThunderMusic
 
G

Guest

use SQLCommand ExecuteScalar function
that will return a single value to you.

cmd.ExecuteScalar()

Hope it helps
 
J

Jim in Arizona

ThunderMusic said:
Hi,

First of all, for just a single value like this, I'd go with
objCommand.ExecuteScalar() (instead of ExecuteReader()) and just cast the
result to string like this :

string yourVar = objCommand.ExecuteScalar().ToString();

One thing to not tought, if your command returns a DBNull you will have an
exception, so the best way to go if you don't know for sure there will be a
result is like this :

object obj = objCommand.ExecuteScalar();
string yourVar = (obj == DBNull.Value) ? string.Empty : obj.ToString();

you can also put null instead of string.Empty because string is a nullable
type, it's your choice... ;)

I hope it helps

ThunderMusic

That's exactly what I needed. Thanks Thunder.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,770
Messages
2,569,583
Members
45,074
Latest member
StanleyFra

Latest Threads

Top