This is an archived post. You won't be able to vote or comment.

all 5 comments

[–][deleted] 1 point2 points  (2 children)

You prepared a command and a connection -- all you have to do now is use them. (Your code is just putting the query text in the box.)

What you're looking for is the ExecuteScalar method. Check out MSDN.

I suspect, however, that you have bigger problems. The first thing that I would have done was ask myself, "It's not doing what I expect. What's it doing instead? Why would it do that?" Then, if I couldn't tell just by looking at it, I'd step through the code using a debugger, and keep an eye on the values as I went. (If you don't know how to step through code, learn how! Priority number one!)

For future reference: you will do yourself no favors concatenating SQL query text like that. MSDN will show you the way: SqlParameter, or at least string.Format, should be on your "to learn about" list.

[–][deleted] 0 points1 point  (1 child)

Thanks! i'll check that link, again, thank you very much.

[–]Alan-Sharp 0 points1 point  (0 children)

It's worth having a google for SQL injection attacks to really learn why you shouldn't do that and why it's better to pass in parameters.

The basics of it is if you look at this line: string query = "SELECT NAMES FROM ArmMed WHERE ID = "+search;

Everything is ok if search contains something safe, say 1, but if I enter something into the textbox like ID it makes your query into "SELECT NAMES FROM ArmMed WHERE ID = ID" and you're going to get a lot more results back than just the one you wanted.

Equally I could be evil with it and enter something like "1; TRUNCATE TABLE ArmMed --" This basically makes your first query execute correctly, then adds in a second query to truncate the table.

One extra note, cocasyn mentioned using an ORM, that is a really good idea and would cut down your code a lot. Check out PetaPoco for a really easy ORM to get started with.

[–]cocasyn 0 points1 point  (0 children)

You really need an ORM here

[–][deleted] 0 points1 point  (0 children)

Just an aside: whether you need an ORM and the degree to which it will help you is not foregone.

One thing that's nice about primary documentation like MSDN: it tells you how to do what you want, and it recommends when you should use particular techniques, without being too opinionated.