Select 语句在 SqlCommand 中无法正常工作

Select statement not working properly in SqlCommand

我正在使用以下代码在 ASP.Net 网络应用程序的网页上创建 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 服务器中执行相同的命令,它会正确执行。

那么我做错了什么?这是事情的 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}" 中将值转换为字符串如果您当前的文化设置没有为您提供第一个所需的格式。