选择语句在SqlCommand中无法正常工作

时间:2015-01-20 01:27:10

标签: c# sql asp.net sql-server

我使用以下代码在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仍显示在具有日期时间的网页上。

enter image description here

如果我在Sql Server中运行相同的命令,它会正确执行。

enter image description here

那我在这里做错了什么?这是问题的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>

2 个答案:

答案 0 :(得分:3)

这将格式化日期:

<asp:BoundField DataField ="WeekEndingDate" HeaderText="Week Ending Date" ItemStyle-Width="150px" dataformatstring="{0:MM-dd-yyyy}"/>

答案 1 :(得分:1)

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}",如果您当前的文化设置不在&#39 ; t给你第一个你想要的格式。