簡體   English   中英

TextBox =從Sql選擇將datetime轉換為Date

[英]TextBox = Select From Sql convert datetime to Date

嗨,我想將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個參數

您需要先將其轉換為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");

第一:使用參數

第二:在嘗試格式化之前從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

或使用“精簡程序”之類的工具:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM