搜索网格视图 asp.net

Search gridview asp.net

我在 asp.net 程序中进行日期范围搜索时出现以下错误。

Conversion failed when converting date and/or time from character string

这是搜索代码。请帮忙。我还想在我的网格视图中只显示日期而不显示日期和时间。

<asp:GridView ID="GridView1" runat="server" AllowPaging="True" AllowSorting="True"
        AutoGenerateColumns="False" DataKeyNames="ID" DataSourceID="SqlDataSource2">
        <Columns>
            <asp:BoundField DataField="ID" HeaderText="ID" InsertVisible="False" ReadOnly="True"
                SortExpression="ID" />
            <asp:BoundField DataField="Story_number" HeaderText="Story_number" SortExpression="Story_number" />
            <asp:BoundField DataField="Date" HeaderText="Date" SortExpression="Date" />
            <asp:BoundField DataField="Memory_card" HeaderText="Memory_card" SortExpression="Memory_card" />
            <asp:BoundField DataField="Story_Name" HeaderText="Story_Name" SortExpression="Story_Name" />
        </Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource2" runat="server" ConnectionString="<%$ ConnectionStrings:IngestConnectionString %>"
        SelectCommand="SELECT ID, Story_number, Date, Memory_card, Story_Name FROM Library WHERE (Story_Name LIKE '%' + @Story_Name + '%') AND (Story_number LIKE '%' + @Story_number + '%')   AND (@startDate IS NULL OR Date >= @startdate) AND (@enddate IS NULL or Date <= @enddate)">
        <SelectParameters>
            <asp:ControlParameter ControlID="TextBox1" Name="Story_Name" PropertyName="Text"
                DefaultValue="%" />
            <asp:ControlParameter ControlID="TextBox2" DefaultValue="%" Name="Story_number" PropertyName="Text" />
            <asp:ControlParameter ControlID="TextBox3" DefaultValue="" Name="startdate" PropertyName="Text" />
            <asp:ControlParameter ControlID="TextBox4" Name="enddate" DefaultValue="" PropertyName="Text" />
 </asp:SqlDataSource>

您不应在日期后附加 % 符号。这是一个仅适用于 LIKE 表达式的通配符运算符。

你只需要

(Date BETWEEN @startdate AND @enddate)

筛选日期范围。

要允许空日期,您必须切换到布尔逻辑而不是使用 between:

(@startDate IS NULL OR Date >= @startdate) AND (@enddate IS NULL or Date <= @enddate)

下面的代码解决了向数据库传递null的问题。

CancelSelectOnNullParameter="False"

代码如下

<asp:SqlDataSource ID="SqlDataSource2" runat="server"
        CancelSelectOnNullParameter="False"
        ConnectionString="<%$ ConnectionStrings:IngestConnectionString %>"
        SelectCommand="SELECT ID, Story_number, Date, Memory_card, Story_Name FROM Library WHERE (Story_Name LIKE '%' + @Story_Name + '%') AND (Story_number LIKE '%' + @Story_number + '%') AND (@startdate IS NULL OR @startdate = '' OR Date >= @startdate) AND (@enddate IS NULL OR @enddate = '' OR Date <= @enddate)">
            <SelectParameters>