Datareader(simple)

  • Thread starter Thread starter Cdude
  • Start date Start date
C

Cdude

SqlCommand findProducts = new SqlCommand("SELECT PRODUCT_TYPE_ID FROM
PRODUCT_TYPE WHERE [NAME] = 'Meals'", sqlConnection1);

This command returns a value of 17. How can i insert this value into
a string variable? Please help . I tried this but it wouldnt work

SqlDataReader myReader = findProducts.ExecuteReader();
while (myReader.Read())
{
ProdTypeID =
int.Parse(myReader["PRODUCT_TYPE_ID"].ToString());
}
 
If it only returns a single cell, then ExecuteScalar() might be an
easier option; since you state that you want a string, the easiest
option would then be:

string foo = Convert.ToString(findProducts.ExecuteScalar());

How to best use data-reader depends on whether PRODUCT_TYPE_ID is an int
or a [n][var]char;
if int:
string foo = reader.GetInt32(0).ToString();
if [n][var]char:
string foo = reader.GetString(0);

You could also use:
string foo = Convert.ToString(reader[0]);
or
string foo = Convert.ToString(reader["PRODUCT_TYPE_ID"]);

Marc
 

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

Back
Top