如何将此过滤器表达式更改为参数化查询?

时间:2013-07-22 18:09:17

标签: c# javascript asp.net webforms

早上好, 如何将此过滤器表达式转换为参数化查询但仍显示在gridview中?现在,如果我搜索%^&%*,它会崩溃。

C#:

public static bool IsDate(Object obj)
        {
            string strDate = obj.ToString();
            try
            {
                DateTime dt = DateTime.Parse(strDate);
                if (dt != DateTime.MinValue && dt != DateTime.MaxValue)
                    return true;
                return false;
            }
            catch
            {
                return false;
            }
        }

 protected void BtnWinnersSearch_Click(object sender, EventArgs e)
        {

            string searchText = txtWinnersSearch.Text.Replace("'", "''").Trim();
            bool isDate = IsDate(searchText);

            GridViewWinners.Visible = true;

            if (isDate == true)
            {
                SqlDataSource4.FilterExpression = "dob" + " ='" + Convert.ToDateTime(searchText).ToString("yyyy-MM-dd") + "'";
            }
            else
            {
                SqlDataSource4.FilterExpression = "nickname like '%" + searchText + "%' or username like '%" + searchText +
                    "%' or clubnumber like '%" + searchText + "%' or firstname like '%" +
                    searchText + "%' or lastname like '%" + searchText +
                    "%' or email like '%" + searchText + "%'";
            }
        }

ASP:

<asp:Panel ID="pnlWinners" DefaultButton="BtnWinnersSearch" runat="server" Visible="False">
        <table>
        <tr>
            <td align="center"><b>MANAGE WINNERS</b> - 
            <asp:Button ID="BtnWinnerAdd" runat="server" Text="Add" 
                    onclick="BtnWinnerAdd_Click" /> | 
                <asp:TextBox ID="txtWinnersSearch" runat="server" MaxLength="220"></asp:TextBox>
                    <asp:Button ID="BtnWinnersSearch"
                    runat="server" Text="Search" onclick="BtnWinnersSearch_Click"  />
            </td>
        </tr>
        <tr>
        <td>
                <asp:GridView ID="GridViewWinners" runat="server" AutoGenerateColumns="False" DataKeyNames="PlayerID"
                DataSourceID="SqlDataSource4" 
                EmptyDataText="There are no winners to display." CellPadding="4"
                AllowSorting="True" 
                onsorting="GridViewWinners_Sorting" 
                ForeColor="#333333" 
                Visible="False"
                onselectedindexchanged="GridViewWinners_SelectedIndexChanged" 
                    FooterStyle-Wrap="False" HeaderStyle-Wrap="False" PagerStyle-Wrap="False" 
                    RowStyle-Wrap="False" SelectedRowStyle-Wrap="False" Font-Overline="False" >
                <AlternatingRowStyle BackColor="White" ForeColor="#284775" HorizontalAlign="Center" 
                        VerticalAlign="Middle" Wrap="False" />
                <Columns>
                    <asp:CommandField ShowSelectButton="True"/>
                    <asp:BoundField DataField="PlayerID" HeaderText="PlayerID" InsertVisible="False" 
                        ReadOnly="True" SortExpression="PlayerID" Visible="False" />
                        <asp:BoundField DataField="Nickname" HeaderText="Nickname" 
                        SortExpression="Nickname" ItemStyle-Wrap="False">
                    <ItemStyle Wrap="False" />
                    </asp:BoundField>
                    <asp:BoundField DataField="LastName" HeaderText="Last Name" 
                        SortExpression="LastName" ItemStyle-Wrap="False">
                    <ItemStyle Wrap="False" />
                    </asp:BoundField>
                    <asp:BoundField DataField="FirstName" HeaderText="First Name" 
                        SortExpression="FirstName" />
                    <asp:BoundField DataField="UserName" HeaderText="UserName" 
                        SortExpression="UserName" />
                    <asp:BoundField DataField="ClubNumber" HeaderText="Account Number" 
                        SortExpression="ClubNumber" />
                    <asp:BoundField DataField="Email" HeaderText="Email" 
                        SortExpression="Email" />
                    <asp:BoundField DataField="DOB" HeaderText="D.O.B." 
                        DataFormatString="{0:d}" SortExpression="DOB" />
                </Columns>
                <EditRowStyle BackColor="#999999" />
                <FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
                <HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" 
                        HorizontalAlign="Center" VerticalAlign="Middle" />
                <PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
                <RowStyle BackColor="#F7F6F3" ForeColor="#333333" 
                        HorizontalAlign="Center" VerticalAlign="Middle" />
                <SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
                <SortedAscendingCellStyle BackColor="#E9E7E2" />
                <SortedAscendingHeaderStyle BackColor="#506C8C" />
                <SortedDescendingCellStyle BackColor="#FFFDF8" />
                <SortedDescendingHeaderStyle BackColor="#6F8DAE" />
            </asp:GridView>
            </td>
            </tr>
            </table>
            </asp:Panel>
             <asp:SqlDataSource ID="SqlDataSource4" runat="server" 
                ConnectionString="****" 
                ProviderName="***" 
                SelectCommand="SELECT [PlayerID], [Nickname], [UserName], [ClubNumber], [FirstName], [Email], [LastName], [DOB] FROM [Players] order by lastname ASC">
            </asp:SqlDataSource>
</asp:Content>

enter image description here

错误:

  

Like运算符出错:字符串模式'%@#%$%'无效。

     

描述:执行期间发生了未处理的异常   当前的网络请求。请查看堆栈跟踪了解更多信息   有关错误的信息以及它在代码中的起源。

     

异常详细信息:System.Data.EvaluateException:Like中的错误   operator:字符串模式'%@#%$%'无效。

     

来源错误:

     

执行期间生成了未处理的异常   当前的网络请求。有关的来源和位置的信息   可以使用下面的异常堆栈跟踪来识别异常。

     

堆栈追踪:

     

[EvaluateException:Like运算符出错:字符串模式   '%@#%$%'无效。] System.Data.LikeNode.AnalyzePattern(String   pat)+1251846 System.Data.LikeNode.Eval(DataRow row,DataRowVersion   版本)+345 System.Data.BinaryNode.EvalBinaryOp(Int32 op,   ExpressionNode为left,ExpressionNode为right,DataRow为row,DataRowVersion   版本,Int32 [] recordNos)+13013
  System.Data.BinaryNode.Eval(DataRow row,DataRowVersion version)+29
  System.Data.BinaryNode.EvalBinaryOp(Int32 op,ExpressionNode left,   ExpressionNode对,DataRow行,DataRowVersion版本,Int32 []   recordNos)+13013 System.Data.BinaryNode.Eval(DataRow row,   DataRowVersion版)+29
  System.Data.BinaryNode.EvalBinaryOp(Int32 op,ExpressionNode left,   ExpressionNode对,DataRow行,DataRowVersion版本,Int32 []   recordNos)+13013 System.Data.BinaryNode.Eval(DataRow row,   DataRowVersion版)+29
  System.Data.BinaryNode.EvalBinaryOp(Int32 op,ExpressionNode left,   ExpressionNode对,DataRow行,DataRowVersion版本,Int32 []   recordNos)+13013 System.Data.BinaryNode.Eval(DataRow row,   DataRowVersion版)+29
  System.Data.BinaryNode.EvalBinaryOp(Int32 op,ExpressionNode left,   ExpressionNode对,DataRow行,DataRowVersion版本,Int32 []   recordNos)+13013 System.Data.BinaryNode.Eval(DataRow row,   DataRowVersion版)+29
  System.Data.DataExpression.Invoke(DataRow行,DataRowVersion版本)   +151 System.Data.Index.AcceptRecord(Int32 record,IFilter filter)+103 System.Data.Index.InitRecords(IFilter filter)+303 System.Data.Index..ctor(DataTable table,Int32 [] ndexDesc,   IndexField [] indexFields,Comparison`1比较,DataViewRowState   recordStates,IFilter rowFilter)+491
  System.Data.DataTable.GetIndex(IndexField [] indexDesc,   DataViewRowState recordStates,IFilter rowFilter)+228
  System.Data.DataView.UpdateIndex(布尔力,布尔值fireEvent)   +165 System.Data.DataView.UpdateIndex(布尔强制)+12 System.Data.DataView.SetIndex2(String newSort,DataViewRowState   newRowStates,IFilter newRowFilter,Boolean fireEvent)+113
  System.Data.DataView.SetIndex(String newSort,DataViewRowState   newRowStates,IFilter newRowFilter)+17
  System.Data.DataView.set_RowFilter(String value)+160
  System.Web.UI.WebControls.FilteredDataSetHelper.CreateFilteredDataView(数据表   table,String sortExpression,String filterExpression,IDictionary   filterParameters)+396
  System.Web.UI.WebControls.SqlDataSourceView.ExecuteSelect(DataSourceSelectArguments   论点)+2012
  System.Web.UI.DataSourceView.Select(DataSourceSelectArguments   参数,DataSourceViewSelectCallback回调)+21
  System.Web.UI.WebControls.DataBoundControl.PerformSelect()+ 143 3   System.Web.UI.WebControls.BaseDataBoundControl.DataBind()+74
  System.Web.UI.WebControls.GridView.DataBind()+ 4
  System.Web.UI.WebControls.BaseDataBoundControl.EnsureDataBound()+66
  System.Web.UI.WebControls.CompositeDataBoundControl.CreateChildControls()   +75 System.Web.UI.Control.EnsureChildControls()+ 102 System.Web.UI.Control.PreRenderRecursiveInternal()+42
  System.Web.UI.Control.PreRenderRecursiveInternal()+ 1755   System.Web.UI.Control.PreRenderRecursiveInternal()+ 1755   System.Web.UI.Control.PreRenderRecursiveInternal()+ 1755   System.Web.UI.Control.PreRenderRecursiveInternal()+ 1755   System.Web.UI.Control.PreRenderRecursiveInternal()+ 1755   System.Web.UI.Page.ProcessRequestMain(布尔   includeStagesBeforeAsyncPoint,Boolean includeStagesAfterAsyncPoint)   2496

此致 Christopher Witalis Peterson

2 个答案:

答案 0 :(得分:1)

您是否尝试过将参数化搜索文本设置为'%'+ @ SearchText +'%'?

答案 1 :(得分:0)

 SelectCommand="SELECT [PlayerID], [Nickname], [UserName], [ClubNumber], [FirstName], [Email], [LastName], [DOB] FROM [Players] where Nickname like '%'+@Nickname+'%' order by lastname ASC">
                <SelectParameters>
                     <asp:ControlParameter ControlID="txtWinnersSearch" Name="Nickname" PropertyName="Text" Type="String"/>
                </SelectParameters>
            </asp:SqlDataSource>