我试图根据 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.