WEI ZHUANG GOH
WEI ZHUANG GOH

Reputation: 333

Cannot search on gridview C# aspnet

I'm implementing a search bar to filter GridView1. I followed this tutorial but when it doesnt work. I want to filter the UserID and show only the specific output match the user input. I clicked on search but nothing work, it just refreshed the page and nothing else.

enter image description here

aspx

<%@ Page Title="" Language="C#" MasterPageFile="~/Manager.Master" AutoEventWireup="true" CodeBehind="ExceptionReport.aspx.cs" Inherits="Bracelet.ExceptionReport" %>

<%@ Register Assembly="Microsoft.ReportViewer.WebForms" Namespace="Microsoft.Reporting.WebForms" TagPrefix="rsweb" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">



</asp:Content>



<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
    <div class="col-md-10">
                    <div class="content-box-large">
                            <div class="panel-heading">
                    <div class="panel-title">Admin Log Report</div>
                </div>

                    <asp:TextBox ID="txtSearch" runat="server" />
            <asp:Button Text="Search" runat="server"/>

                <div class="panel-body">

        <asp:GridView ID="GridView1" runat="server" AllowSorting="True" AutoGenerateColumns="False" DataKeyNames="UserID">
            <Columns>
                <asp:BoundField DataField="UserID" HeaderText="UserID" ReadOnly="True" SortExpression="UserID" />
                <asp:BoundField DataField="UserName" HeaderText="UserName" SortExpression="UserName" />
                <asp:BoundField DataField="UserEmail" HeaderText="UserEmail" SortExpression="UserEmail" />
                <asp:BoundField DataField="logtime" HeaderText="logtime" SortExpression="logtime" />
            </Columns>
        </asp:GridView>
                      </div>
</div>
        <asp:LinqDataSource ID="LinqDataSource2" runat="server" ContextTypeName="Bracelet.BraceletDataContext" EntityTypeName="" TableName="Users">
        </asp:LinqDataSource>
        <asp:LinqDataSource ID="LinqDataSource1" runat="server" ContextTypeName="Bracelet.BraceletDataContext" EntityTypeName="" TableName="Users" Where="UserRole == @UserRole">
            <WhereParameters>
                <asp:Parameter DefaultValue="Admin" Name="UserRole" Type="String" />

            </WhereParameters>
        </asp:LinqDataSource>


    </div>
</asp:Content>

Full code .cs

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.Configuration;
using System.Data.SqlClient;
using System.Text.RegularExpressions;


namespace Bracelet
{
    public partial class ExceptionReport : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!this.IsPostBack)
            {
                this.BindGrid();
            }
        }

        protected void Search(object sender, EventArgs e)
        {
            this.BindGrid();
        }

        private void BindGrid()
        {
            string constr = ConfigurationManager.ConnectionStrings["BraceletConnectionString"].ConnectionString;
            using (SqlConnection con = new SqlConnection(constr))
            {
                using (SqlCommand cmd = new SqlCommand())
                {

                    cmd.CommandText = "SELECT UserID, UserName, UserEmail, logtime FROM [User] WHERE UserID LIKE '%' + @UserID + '%'";

                    cmd.Connection = con;
                    cmd.Parameters.AddWithValue("@UserID ", txtSearch.Text.Trim());
                    DataTable dt = new DataTable();
                    using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
                    {
                        sda.Fill(dt);
                        GridView1.DataSource = dt;
                        GridView1.DataBind();
                    }
                }
            }
        }

        protected void OnPageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            GridView1.PageIndex = e.NewPageIndex;
            this.BindGrid();
        }
    }
}

Upvotes: 1

Views: 807

Answers (1)

Albert D. Kallal
Albert D. Kallal

Reputation: 49039

Not too bad.

but, there are few errors and issues.

first up, you have search button - but it has no "id" assigned.

You probably should get in the habit of simple drag + drop the button in from the tool box.

So, we now have this for the button and the grid:

<asp:TextBox ID="txtSearch" runat="server" />
<asp:Button ID="cmdSearch" runat="server" Text="Search" />


<asp:GridView ID="GridView1" runat="server" AllowSorting="True" AutoGenerateColumns="False" DataKeyNames="UserID">
    <Columns>
        <asp:BoundField DataField="UserID" HeaderText="UserID" ReadOnly="True" SortExpression="UserID" />
        <asp:BoundField DataField="UserName" HeaderText="UserName" SortExpression="UserName" />
        <asp:BoundField DataField="UserEmail" HeaderText="UserEmail" SortExpression="UserEmail" />
        <asp:BoundField DataField="logtime" HeaderText="logtime" SortExpression="logtime" />
    </Columns>
</asp:GridView>

NOTE carefull in above, how we gave the button a "ID"

So, our basic code to load up the grid?

FYI: huge love, hugs, high-5's for checking is-post back!!! (always, always do that!!!).

So, our code to load things up can thus look like this:

   protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
            this.BindGrid();
    }


    void BindGrid()
    {
        string constr = ConfigurationManager.ConnectionStrings["BraceletConnectionString"].ConnectionString;

        using (SqlConnection con = new SqlConnection(constr))
        {
            using (SqlCommand cmd = new SqlCommand("SELECT UserID, UserName, UserEmail, logtime FROM [User]", con))
            {

                // optional text box filter (blank = all)
                if (txtSearch.Text != "")
                {
                    cmd.CommandText += " WHERE UserID LIKE '%' + @UserID + '%'";
                    cmd.Parameters.Add("@UserID", SqlDbType.Text).Value = txtSearch.Text;
                }
                con.Open();
                DataTable dt = new DataTable();
                dt.Load(cmd.ExecuteReader());
                GridView1.DataSource = dt;
                GridView1.DataBind();
                }
            }
        }
    }

Note how we did not need that data adaptor - not needed.

However, we still not created the code stub for the button click (that's why your code is not working - you did not give your button a "id"

So, in the designer - double click on the button. That will create the "event" for you, and jump to the code editor, and we have this:

    protected void cmdSearch_Click(object sender, EventArgs e)
    {
        this.BindGrid();
    }

so, in general - don't type in the "event" stubs for a button - double click on the button - it will create + wire it up for you.

Note close, if I flip back to mark-up, the button has become this:

<asp:Button ID="cmdSearch" runat="server" Text="Search" OnClick="cmdSearch_Click" />

Upvotes: 2

Related Questions