ShmuelCohen
ShmuelCohen

Reputation: 472

Converting DataSet to String or Int

I have a function that gets a SQL command and returns a dataset. Now I'm trying to run this string command:

@"SELECT ProductPrice 
FROM Products 
Where ProductPrice IN 
(
  SELECT ProductPrice 
  FROM Products 
  WHERE  ProductName =N'" 

+ listBox1.Text 
+ "')").Tables[0].Rows[0].ToString()

ProductPrice is an INT
ProductName is a NVARCHAR

I'm getting this result in the textbox:

' System.Data.DataRow '

BTW : This is a SCHOOL PROJECT! I know this may be vulnerable to SQL Injection

Upvotes: 1

Views: 12519

Answers (2)

David
David

Reputation: 73564

Since this is a homework question, I'm going to stick to the guidelines for homework questions and try to be helpful without giving you a full answer.

  • Try to provide explanation that will lead the asker in the correct direction. Genuine understanding is the real goal for students, but trying to provide that is seldom unappreciated for any question.
  • It's usually better not to provide a complete code sample if you believe it would not help the student, using your best judgment. You can use pseudo-code first, and, in the spirit of creating a programming resource, you may come back after a suitable amount of time and edit your response to include more complete code. This way, the student still has to write their own code, but a full solution can become available after the assignment has ended.

First, you're missing some code in your sample, but based on the results, I'm assuming that you have something like this in your code:

TextboxResults.Text = MyTable.Rows[0].ToString();

The reason you're getting System.Data.DataRow is that you're only referencing the row (the first row in the table that's filled by your data adapter), which is a collection of objects.

Hint: In your select statement, the price is in the first element inside (0 based index) the Row that you're already referencing.

Shorter version: You're referencing the first row of the table. You need to reference the contents of the first cell in the first row in the table.

Since being a good developer often means knowing how to use search, I'd Google the following phrase and apply what I've just told you and you should have your answer:

how to access a particular datarow's cell in a table

Second hint:

If I were going to write to the contents of the first cell in the first row it would look like this:

myTable.Rows[0][0] = 1.99;

instead of

myTable.Rows[0] = 1.99;

Upvotes: 2

Gena
Gena

Reputation: 187

Shmulik,

I guess you try to print using dataRow.ToString(). C# does not know how to print an object of type DataRow since the object may contain different columns. If you want to print ProductPrice, try dataRow[0].ToString() instead.

Upvotes: 1

Related Questions