c# - How to define variables while reading them from a SqlDataReader (returning all rows) -


i have table has 14 rows in want return declare each cell variable. here have tried:

using (sqlconnection conn1 = new sqlconnection(configurationmanager.connectionstrings["2012ssms"].connectionstring))         {             sqlcommand cmd1 = new sqlcommand(@"select [question], [answer]              [mytable]", conn1);             conn1.open();             using (sqldatareader reader1 = cmd1.executereader())             {                 while (reader1.hasrows)                 {                     reader1.getname(0);                     reader1.getname(1);                      while(reader1.read())                     {                         string question(1) = reader1.getstring(0); //errors here                         string answer(1) = reader1.getstring(1); //and here                     }                     reader1.nextresult();                 }             } } 

my hope return declared variables question1 - question14 , answer1 - answer14. how go doing this?

well, if want use 14 different names, define 14 string variables questions , 14 string variable answers. frankly ridicolous when have @ disposal lists , other collection classes.

for example

define class question/answer

public class questionanswer {      public string question {get;set;}      public string answer {get;set;} } 

then modify code create list<questionanswer>

list<questionanswer> listofquestionsandanswers = new list<questionanswer>(); using (sqlconnection conn1 = new sqlconnection(configurationmanager.connectionstrings["2012ssms"].connectionstring)) {     sqlcommand cmd1 = new sqlcommand(@"select [question], [answer]                                         [mytable]", conn1);     conn1.open();     using (sqldatareader reader1 = cmd1.executereader())     {            while(reader1.read())            {                questionanswer qa = new questionanswer();                qa.question = reader1.getstring(0);                 qa.answer = reader1.getstring(1);                 listofquestionsandanswers.add(qa);            }     } } 

now use question in list using following syntax

string aquestion = listofquestionsandanswers[0].question; string ananswer = listofquestionsandanswers[0].answer; 

and, finally, suggest spend bit of time learn how use dapper shown in answer of mr. gravell.


Comments

Popular posts from this blog

commonjs - How to write a typescript definition file for a node module that exports a function? -

openid - Okta: Failed to get authorization code through API call -

ios - Change Storyboard View using Seague -