Question

I have a lotto draw method which should find the winning ticket from the database of purchased tickets. But I am not able to display the results from the query. (I know this isn't how the Lotto really works, I'll come to randomizing the numbers later :P )

draw.aspx.cs

public void LottoDraw(object sender, EventArgs e)
{
    var connectionstring = "Server=C;Database=lotto;User Id=lottoadmin;Password=password;";

    using (var con = new SqlConnection(connectionstring))  // Create connection with automatic disposal
    {
        con.Open();

        using (var tran = con.BeginTransaction())  // Open a transaction
        {
            // Create command with parameters
            string sql =
                "SELECT TOP 1 * FROM tblLotto ORDER BY NEWID()";
            var cmd = new SqlCommand(sql, con);

            cmd.Transaction = tran;
            cmd.ExecuteNonQuery(); // Execute the query

            tran.Commit();  // commit transaction

            Response.Write("<br />");
            Response.Write("<br />");
            Response.Write("end...");
        }
    }
}
Was it helpful?

Solution

This is because you are using exectue non-query.

To retrieve results you either need to use an SQLReader or an SqlDataAdapter

Personally I find using a DataAdapter easier:

    DataTable t = new DataTable();

    using (SqlConnection c = new SqlConnection(DataConnectionString))
    {
         c.Open();
         // Create new DataAdapter
         using (SqlDataAdapter a = new SqlDataAdapter("SELECT * FROM EmployeeIDs", c))     
         {
              // Use DataAdapter to fill DataTable
              a.Fill(t);
         }
    }

You can then access your data by:

 if(t.Rows.Count == 1){

      String val0 = t.Rows[0]["VAL0"].ToString();
      String val1 = t.Rows[0]["VAL1"].ToString();
      String val2 = t.Rows[0]["VAL2"].ToString();
      String val3 = t.Rows[0]["VAL3"].ToString();
      String val4 = t.Rows[0]["VAL4"].ToString();
      String val5 = t.Rows[0]["VAL5"].ToString();
 }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top