DiH DiH - 3 months ago 25
C# Question

TextBox = Select From Sql convert datetime to Date

Hi i want to bring a value from sql into a textbox as date. I'm using this code:

SqlCommand command = new SqlCommand("select top 1 expirationdate from incomes where memberid='0' or memberid = '" + textBox22.Text + "' order by expirationdate DESC", con);
textBox17.Text = command.ExecuteScalar().ToString("d/M/yyyy");


I get an error: no overload for method “ToString” takes 1 arguments

Answer

You need to first convert it to DateTime. Also use sql paramaters to avoid sql injection.

 SqlCommand command = new SqlCommand("select top 1 expirationdate from incomes where memberid='0' or memberid = @memberId order by expirationdate  DESC", con);
    command.Parameters.AddWithValue("memberId",textBox22.Text);
    var result = command.ExecuteScalar().ToString();
    textBox17.Text = Convert.ToDateTime(result).ToString("d/M/yyyy");