【问题标题】:Setting DateTime as a SqlDataSource parameter for Gridview将 DateTime 设置为 Gridview 的 SqlDataSource 参数
【发布时间】:2012-02-05 22:07:33
【问题描述】:

嘿,我想用我的存储过程显示过去 30 天的某些数据。这是我所做的(aspx.cs 文件):

 protected void Page_Load(object sender, EventArgs e)     
        {
          DateTime toDate, fromDate;
          toDate = DateTime.Now;

          fromDate = toDate.Subtract(new TimeSpan(31, 0, 0, 0));

          SqlDataSource1.SelectParameters.Add("fromDate", DbType.DateTime, fromDate.ToString());
          SqlDataSource1.SelectParameters.Add("toDate", DbType.DateTime, toDate.ToString());                    

    }

这是我的 aspx 文件

 <form id="form1" runat="server">
        <asp:GridView ID="GridView1" runat="server" AllowPaging="True" AllowSorting="True" AutoGenerateColumns="False" Width="232px" DataKeyNames="CustomerId" DataSourceID="SqlDataSource1">
            <Columns>
                <asp:BoundField DataField="CreationDate" HeaderText="CreationDate" SortExpression="CreationDate" />
            </Columns>
        </asp:GridView>
        <br />
        <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:SSEnewConnectionString %>"
            SelectCommand="procCustomer_SelectbyCreationDate" SelectCommandType="StoredProcedure">
            <SelectParameters>
                <asp:Parameter DbType="DateTime" Name="fromDate" />
                <asp:Parameter DbType="DateTime" Name="toDate" />
            </SelectParameters>
        </asp:SqlDataSource>
        </form>

当我测试这个时,我的屏幕出现空白(除了母版页元素)并且没有错误。有什么想法吗?

【问题讨论】:

  • 你那里有数据吗?

标签: c# asp.net gridview sqldatasource


【解决方案1】:

编辑:即使此答案的早期版本已被接受,但看起来我误解了所使用的参数类型。 web controls ParameterCollection 看起来有些糟糕。

我建议将日期值转换为 SQL 格式(坦率地说,这让我很痛苦 - 应尽可能避免字符串转换)。例如:

SqlDataSource1.SelectParameters.Add("fromDate", DbType.DateTime,
    fromDate.ToString("yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture));
SqlDataSource1.SelectParameters.Add("toDate", DbType.DateTime,
    toDate.ToString("yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture));

(对于仅日期类型,更改为 yyyy-MM-dd。)

我自己没有使用过SqlDataSource,但它也看起来就像你两次引入参数 - 一次在标记中,一次在代码中。鉴于您没有标记中的值(包括绑定中),您可能希望从那里删除它们 - 但我在这方面可能是错误的。

如果您的查询没有达到您的预期,您应该检查您的数据库日志(或任何合适的工具)以检查 实际 查询正在执行什么。

【讨论】:

  • 如果我删除 toString() 我得到以下错误“'System.Web.UI.WebControls.ParameterCollection.Add(string, System.Data.DbType, string)'的最佳重载方法匹配”有一些无效的参数”
  • 另外,从 aspx 文件中删除参数似乎可以解决问题……至少我现在在屏幕上得到了一些数据。我不得不使用 toString() 转换...
  • 我也有同样的问题。 .Add 方法只允许使用字符串,在我的情况下,它会导致 SQL 出错。不太确定如何进行。
  • @carny666:不,它真的不仅允许字符串。我建议您提出一个包含适当详细信息的新问题。
  • @carny666:对,是的,第三个参数的类型是string。 (我以前不清楚你的意思。)我不得不承认,当我写这个答案时(很久以前)我怀疑我对SqlDbParameter 感到困惑。这看起来像一个非常糟糕的 API - 不过我会根据一些建议进行编辑。
猜你喜欢
  • 1970-01-01
  • 2012-06-30
  • 1970-01-01
  • 1970-01-01
  • 2010-11-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-12-22
相关资源
最近更新 更多