Search code examples
c#mysqldatareader

Get values of a single column in C# mysql and put it in textbox


I have this table called WeeklySales with 2 columns, DateandTime and Sales. Now, I have 3 textbox on my form. I wanted to get the latest value that was added on the table so I have this string.

    string sql = "SELECT Sales FROM database.weeklysales ORDER BY DateandTime DESC LIMIT 3";

Now, I have this database(lets say that month is the date),

 DateandTime | Sales
 March       | $300
 February    | $500
 January     | $400

and get this result with that string:

 Sales
 $300
 $500
 $400

Now, I wanted to put the first row into first textbox, then second row to second textbox and so on... Now, I do not know what to out in inside the Datareader...

        try
        {
            con.Open();
            using (reader = cmd.ExecuteReader())
            {
               first.Text = ?
               second.Text = ?
               third.Text = ?
            }
        }
        finally
        {
            con.Close();
        }

I have searched but they only get the first row unfortunately.


Solution

  • Since you only have 3 text boxes to fill - no loop just advance the reader manually.

    MySqlDataReader dr = cmd.ExecuteReader();
    dr.Read();
    first.Text = dr.GetValue(0).ToString();
    dr.Read();
    second.Text = dr.GetValue(0).ToString();
    dr.Read();
    third.Text = dr.GetValue(0).ToString();