[英]Select statement not working properly in SqlCommand
我正在使用以下代碼在ASP.Net Web應用程序的網頁上創建sql數據網格。
private void BindGrid()
{
string strConnString = "server= N-1077; Trusted_Connection=yes; database=Slaughter; connection timeout=30";
using (SqlConnection con = new SqlConnection(strConnString))
{
using (SqlCommand cmd = new SqlCommand("SELECT WeekEndingDate = CONVERT(date, Week_Ending_Date, 103), Week_Number, North_Island, South_Island FROM Slaughter ORDER BY WeekEndingDate DESC"))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = con;
sda.SelectCommand = cmd;
using (DataTable dt = new DataTable())
{
sda.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
}
}
}
我不確定為什么,但是當我調用select語句時-“ SELECT WeekEndingDate = CONVERT(date,Week_Ending_Date,103),Week_Number,North_Island,South_Island FROM Slaughter ORDER BY WeekEndingDate DESC”-WeekEndingDate仍顯示在網頁上日期時間。
如果我在Sql Server中運行相同的命令,它將正確執行。
那我在做什么錯呢? 這是html方面的內容,以防萬一是問題所在。
<div style="width: 1250px; height: 300px; overflow: auto">
<asp:GridView ID="GridView1" HeaderStyle-BackColor="#6699ff" HeaderStyle-ForeColor="Black" RowStyle-BackColor="#ccffff" AlternatingRowStyle-BackColor="White"
AlternatingRowStyle-ForeColor="#000" runat="server" AutoGenerateColumns ="false" AllowPaging="false" OnPageIndexChanging="OnPageIndexChanging" AllowSorting="True">
<Columns>
<asp:BoundField DataField ="WeekEndingDate" HeaderText="Week Ending Date" ItemStyle-Width="150px" />
<asp:BoundField DataField ="Week_Number" HeaderText="Week Number" ItemStyle-Width="150px" />
<asp:BoundField DataField ="North_Island" HeaderText="North Island" ItemStyle-Width="150px" />
<asp:BoundField DataField ="South_Island" HeaderText="South Island" ItemStyle-Width="150px" />
</Columns>
</asp:GridView>
</div>
這將格式化日期:
<asp:BoundField DataField ="WeekEndingDate" HeaderText="Week Ending Date" ItemStyle-Width="150px" dataformatstring="{0:MM-dd-yyyy}"/>
CONVERT(date, Week_Ending_Date, 103)
將Week_Ending_Date的值轉換為返回數據集中的日期數據類型。 .NET將其作為DateTime接收,並且DateTime的默認字符串格式包括時間值。 這就是為什么您的網頁上顯示時間。 如果您不希望顯示時間,請在SQL中將值轉換為字符串: CONVERT(nvarchar(10), Week_Ending_Date, 103)
或ASP標記: dateformatstring="{0:d}"
或dateformatstring="{0:dd-MM-yyyy}"
如果您當前的區域性設置未提供您想要的第一個格式。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.