title: ASP.Net C# - Using a DataTable
body: <p>I hope this makes sense. I'm familiar with using DataReaders, however I think using a DataTable in this instance makes sense.  I have a database table that includes 'questions' and I want to implement a facility to be able to browse through the questions on a website.</p>
  
  <p>So, simplified, there's a label to output the question (lblQuestion) and a back button and a forward button to go to the previous/next question.</p>
  
  <p>Is the following code/saving the DataTable in a Session object the most efficient way to do this?</p>
  
  <pre><code>protected void Page_Load(object sender, EventArgs e)
  {
      if (!(Page.IsPostBack))
      {
          getQuestions();
          int questionCounter = 1;
          ViewState["questionCounter"] = questionCounter;
          lblCounter.Text = questionCounter.ToString();
      }
  }
  
  protected void getQuestions()
  {
      string connStr = ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString;
      MySqlConnection conn = new MySqlConnection(connStr);
      MySqlDataReader reader;
  
      string cmdText = "SELECT * FROM questions WHERE approved='Y' AND module_id=1";
      MySqlCommand cmd = new MySqlCommand(cmdText, conn);
  
      try
      {
          conn.Open();
          reader = cmd.ExecuteReader();
  
          DataTable dt1 = new DataTable();
          dt1.Load(reader);
          reader.Close();
          Session["dt1"] = dt1;
  
          lblQuestion.Text = dt1.Rows[0]["question"].ToString();
      }
      catch
      {
          lblError.Text = "Database connection error - failed to get questions.";
      }
      finally
      {
          conn.Close();
      }
  }
  
  protected void btnNext_Click(object sender, EventArgs e)
  {
      int questionCounter = Convert.ToInt32(ViewState["questionCounter"]);
      DataTable dt1 = (DataTable)Session["dt1"];
  
      if (questionCounter &lt; dt1.Rows.Count)
      {
          questionCounter++;
          lblQuestion.Text = dt1.Rows[questionCounter-1]["question"].ToString();
  
          ViewState["questionCounter"] = questionCounter;
          lblCounter.Text = questionCounter.ToString();
      }
      else
      {
          lblQuestion.Text = "the end of questions.";
      }
  }
  
  protected void btnBack_Click(object sender, EventArgs e)
  {
      int questionCounter = Convert.ToInt32(ViewState["questionCounter"]);
      DataTable dt1 = (DataTable)Session["dt1"];
  
      if (questionCounter &gt; 1)
      {
          questionCounter--;
          lblQuestion.Text = dt1.Rows[questionCounter-1]["question"].ToString();
  
          ViewState["questionCounter"] = questionCounter;
          lblCounter.Text = questionCounter.ToString();
      }
      else
      {
          lblQuestion.Text = "the beginning of questions.";
      }
  }
  </code></pre>