简体   繁体   English

在Gridview中搜索数据c#asp.net

[英]searching data in Gridview c# asp.net

I am new to c# asp.net. 我是C#asp.net的新手。 How to search data in a Gridview? 如何在Gridview中搜索数据? My Gridview on page load has all the records from the database. 我在页面加载时的Gridview具有数据库中的所有记录。 I've been searching on it, most is just searching with an empty GridView. 我一直在搜索它,大多数只是使用一个空的GridView搜索。 So yeah, mine is not empty. 是的,我的不是空的。 ERROR: Both DataSource and DataSourceID are defined on 'GridView1'. 错误:DataSource和DataSourceID均在“ GridView1”上定义。 Remove one definition. 删除一个定义。

        String str = "select * from tblEmployee where (Name like '%' + @search + '%')";
        SqlCommand xp = new SqlCommand(str, objsqlconn);
        xp.Parameters.Add("@search", SqlDbType.NVarChar).Value = TextBox1.Text;
        objsqlconn.Open();
        xp.ExecuteNonQuery();
        SqlDataAdapter da = new SqlDataAdapter();
        da.SelectCommand = xp;
        DataSet ds = new DataSet();
        da.Fill(ds, "Name");
        GridView1.DataSource = ds;
        GridView1.DataBind();
        objsqlconn.Close();

You cannot get the data from grid for searching, you need to store you data some where for using search. 您无法从网格中获取数据进行搜索,您需要将数据存储在使用搜索的位置。 That is to store in a ViewState, Session or call DataBase on every search. 即在每次搜索时将其存储在ViewState,Session或调用数据库中。 Bellow code show data stored in a ViewState, you can acces your data any time by just using GridViewData where you can done search. 波纹管代码显示了存储在ViewState中的数据,您可以随时使用GridViewData进行访问,从而可以随时访问数据。 (if you have very large amount of data first preference is calling data from database on every search.) (如果您有大量数据,则首选在每次搜索时从数据库中调用数据。)

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        GridView1.DataSource = GridViewData;
        GridView1.DataBind();
    }
}


public DataSet GridViewData
{
    get
    {
        if (ViewState["GridViewData"] == null)
        {
            String str = "select * from tblEmployee where (Name like '%' + @search + '%')";
            SqlCommand xp = new SqlCommand(str, objsqlconn);
            xp.Parameters.Add("@search", SqlDbType.NVarChar).Value = TextBox1.Text;
            objsqlconn.Open();
            xp.ExecuteNonQuery();
            SqlDataAdapter da = new SqlDataAdapter();
            da.SelectCommand = xp;
            DataSet ds = new DataSet();
            da.Fill(ds, "Name");
            objsqlconn.Close();

            ViewState["GridViewData"] = ds;
        }

        return (DataSet)ViewState["GridViewData"];
    }
}

@Fel...I think you try to bind data to data grid using sqldatasource from design side as well as code behind side @Fel ...我认为您尝试使用sqldatasource从设计方面以及代码的背面将数据绑定到数据网格

1) You need to choose one way to bind the grid 2) if you are binding in design side remove the DataSourceID property from grid view design. 1)您需要选择一种方法来绑定网格2)如果您在设计方面进行绑定,请从网格视图设计中删除DataSourceID属性。 use like this 这样使用

asp:gridview id="grdData" runat="server"

instead of 代替

asp:gridview id="grdData" runat="server" DataSourceID="Datasource1"

please try this code. 请尝试此代码。

 <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="ProjectDemo_Asp.et.Default" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title>Search GridView Record on Button Click By Using C#.Net in Asp.Net</title> </head> <body> <form id="form1" runat="server"> Search By Title : <asp:TextBox ID="txtsearch" runat="server"></asp:TextBox> <asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Search" /> <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" EmptyDataText="There are no data records to display." Width="500px" BorderStyle="Solid" ShowFooter="True"> <Columns> <asp:BoundField DataField="author_name" HeaderText="NAME" /> <asp:BoundField DataField="publisher_name" HeaderText="PUB. NAME" /> <asp:BoundField DataField="title" HeaderText="TITLE" /> <asp:BoundField DataField="publication_year" HeaderText="PUB. YEAR" /> </Columns> <HeaderStyle BackColor="#66CCFF" /> </asp:GridView> </form> </body> </html> 

Now just check the code on your .cs page. 现在,只需检查.cs页面上的代码即可。

using System;
using System.Data;
using System.Data.OleDb;
namespace ProjectDemo_Asp.et
{
    public partial class Default : System.Web.UI.Page
    {
        public string connectionstring = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\\bookstore.mdb;Persist Security Info=False;";
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                DataTable _objdt = new DataTable();
                _objdt = GetDataFromDataBase("");
                if (_objdt.Rows.Count > 0)
                {
                    GridView1.DataSource = _objdt;
                    GridView1.DataBind();
                }
            }
        }

        /// 
        /// Function for binding retribing the data from database
        /// In this i have used Access DB you can use SQL DB to bind the data
         ///
        public DataTable GetDataFromDataBase(string searchtext)
        {
            DataTable _objdt = new DataTable();
            string querystring = "";
            querystring = "select * from Books";
            if (querystring != "")
            {
                querystring += " where title like '%" + txtsearch.Text + "%';";
            }
            OleDbConnection _objcon = new OleDbConnection(connectionstring);
            OleDbDataAdapter _objda = new OleDbDataAdapter(querystring, _objcon);
            _objcon.Open();
            _objda.Fill(_objdt);
            return _objdt;
        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            DataTable _objdt = new DataTable();
            _objdt = GetDataFromDataBase(txtsearch.Text);
            if (_objdt.Rows.Count > 0)
            {
                GridView1.DataSource = _objdt;
                GridView1.DataBind();
            }
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM