Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations derfloh on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

getting a value from a SqlDataReader 2

Status
Not open for further replies.

AT76

Technical User
Joined
Apr 14, 2005
Messages
460
Location
US
Hi,

I'm executing a SQL String that gets the Top 1 value from a column. This value is of type int. I would like to save this value to a variable to be displayed later in a prompt (DisplayValue). Here's my code:

int DisplayValue;
string strSQL = "SELECT TOP 1 VALUE FROM LIST";
SqlCommand cmd = new SqlCommand(strSQL, conn);

//Create/Populate the DataReader
SqlDataReader dr;
dr = cmd.ExecuteReader();

I'm not sure how to pass dr to "DisplayValue". I have tried using:

DisplayValue = dr.GetValue();

But have not been successful. Any advice will be greatly appreciated! Thanks!!!
 
You can try this (VB)

DisplayValue = dr("Value")

 
Assign a variable (in the section that does the Response.Write) from the example in faq855-5662


____________________________________________________________

Need help finding an answer?

Try the Search Facility or read FAQ222-2244 on how to get better results.

 
Since you are returning only one value, I would use
yourvar = cmd.ExecuteScalar

Jim
 
You can either do (C#)

//Create/Populate the DataReader
SqlDataReader dr;
dr = cmd.ExecuteReader();
while (dr.Read())
{
DisplayValue = dr.GetValue(0);
}

or do as JimBenson suggested.

----------------------------------------

TWljcm8kb2Z0J3MgIzEgRmFuIQ==
 
Thanks to everyone!!!
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top