0

ドロップボックス リストと検索語に基づいて GridView データをフィルター処理しようとしています。

私の GridView は現在、SQLdatasource を使用して ASP サーバー側でバインドされています。

onclick_button イベントから C# を介して 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.
4

1 に答える 1

1

aspx コードを確認せずに、次のように GridView1 を定義した可能性があります。

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

に注意してDataSourceIDください。DataSourceIDエラーが示すように、 と の両方を使用することはできませんDataSource。解決策は、イベントで DataSourceID のSelect QueryDataSourceが何であれ、それを設定することだけです。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インジェクションを起こしやすいです -クエリをパラメータ化するようにしてください

于 2013-03-06T00:19:52.440 に答える