尝试过滤GridView时出现问题

本文关键字:问题 GridView 过滤 | 更新日期: 2023-09-27 18:02:20

我试图根据dropbox列表和搜索词过滤我的GridView数据。

我的GridView目前通过ASP服务器端使用SQLdatasource绑定。

我正在尝试通过c#从onclick_button事件中过滤GridView。

下面是我的过滤代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
namespace ViewCDs
{
public partial class _Default : System.Web.UI.Page
{

    protected void btnSearch_Click(object sender, EventArgs e)
    {
        string connstring = @"Data Source=.'SQLEXPRESS;AttachDbFilename=C:'Users'Dave'Documents'cdsCollections.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True";
        SqlConnection sqlcon = new SqlConnection(connstring);
        string str = TextBox1.Text;
        string str2 = DropDownList1.Text;
        string set = "";
        if (str2 == "Artist")
        {
            set = "artist";
        }
        if (str2 == "CD Title")
        {
            set = "cdTitle";
        }
        if (str2 == "Music Genre")
        {
            set = "genre";
        }
        SqlCommand sqlcmd = new SqlCommand("select * from cds where " + set + " like '%" + str + "%'", sqlcon);
        SqlDataAdapter adp = new SqlDataAdapter(sqlcmd);
        DataSet ds = new DataSet();
        adp.Fill(ds);
        if (ds.Tables[0].Rows.Count > 0)
        {
            GridView1.DataSource = ds.Tables[0];
            GridView1.DataBind();
        }
    }
}

}

以及如何在ASP端触发事件:

  <asp:Button ID="Button1" runat="server" Text="Search" onclick="btnSearch_Click" />

这是一个非常标准的布局,通配符查询的结果存储在数据集对象中,如果数据集的计数高于0,那么它应该绑定到我的GridView。但是这个绑定没有发生,我收到了这个错误:

Both DataSource and DataSourceID are defined on 'GridView1'.  Remove one definition.
Description: An unhandled exception occurred during the execution of the current web    request. Please review the stack trace for more information about the error and where it originated in the code. 
Exception Details: System.InvalidOperationException: Both DataSource and DataSourceID are defined on 'GridView1'.  Remove one definition.

尝试过滤GridView时出现问题

在没有看到aspx代码的情况下,您可能会像这样定义GridView1:

<asp:GridView runat="server" ID="GridView1" DataSourceID="SOME_DATA_SOURCE" >

注意DataSourceID。如错误所述,不能同时使用DataSourceIDDataSource。解决方案是仅使用DataSource将其设置为您的DataSourceID的选择查询是-在Page_Load事件。

换句话说,定义没有DataSourceId的GridView:

     <asp:GridView runat="server" ID="GridView1" ... >

后面的代码:

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            DataSet ds =  // Get Data from DB
            GridView1.DataSource = ds.Tables[0];
            GridView1.DataBind();
        }
    }

另一个问题是你有一个安全问题 -你的代码很容易Sql注入 -确保你参数化你的查询