TextBox =选择从Sql将datetime转换为Date

时间:2016-09-08 12:45:12

标签: c#

您好我想将sql中的值作为日期带入文本框。我使用此代码:

 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");

我收到错误:方法“ToString”没有重载需要1个参数

2 个答案:

答案 0 :(得分:2)

您需要先将其转换为DateTime。还使用sql参数来避免sql注入。

 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");

答案 1 :(得分:1)

首先:使用参数

第二:在尝试格式化之前从ExecuteScalar投出值

int memberId = int.Parse(textBox22.Text); // or whatever
DateTime expiry;
using(var command = new SqlCommand(
    "select top 1 expirationdate from incomes where memberid='0' or memberid = @memberid order by expirationdate  DESC", con))
{
    command.Parameters.AddWithValue("memberid", memberId); // again, about 20 ways to do this
    expiry = (DateTime)command.ExecuteScalar();
}
textBox17.Text = expiry.ToString("d/M/yyyy"); // or whatever

或使用像“dapper”这样的工具:

int memberId = int.Parse(textBox22.Text); // or whatever
var expiry = con.QuerySingle<DateTime>(
    "select top 1 expirationdate from incomes where memberid='0' or memberid = @memberid order by expirationdate  DESC",
    new { memberId });
textBox17.Text = expiry.ToString("d/M/yyyy"); // or whatever