0

I have a SQL query like the following:

SELECT Name FROM Customers

My result is as follows:

Name
----
Customer1
Customer2
Customer3
Customer4

I need to pass the customer names to 4 different variables using C# as follows:

string cus1 = Customer1;
string cus2 = Customer2;
string cus3 = Customer3;
string cus4 = Customer4;

Help will be appreciated.

5
  • Do you have a simple example to illustrate how to do it? Commented May 16, 2014 at 18:37
  • 1
    If you are returning your query results to a DataTable, you can get the query result from the DataTable.RowNumber.FieldNumber. Commented May 16, 2014 at 18:49
  • Dan, I thought about using the datatable method but didn't know how. Would you provide me a simple example for future use? Commented May 16, 2014 at 18:54
  • So why did you accept the answer if you still searching for a better solution. @DanBracuk gave you a better way Commented May 16, 2014 at 18:57
  • I am learning C# and SQL and would like to know how to pass values from a Datatable to variables, I am sure that would be very helpful in the future. Commented May 16, 2014 at 19:00

1 Answer 1

2

Read the data into a list, array, or similar. Here I'm using "dapper", but frankly anything would suffice (although DataTable would seems massively overkill for this):

List<string> names = conn.Query<string>("SELECT Name FROM Customers").ToList();

// then just consume them...
foreach(var name in names) {...}
string second = name[1];
// etc
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.