locked
Search in gridview RRS feed

  • Question

  • User-2094959909 posted
    Hello everyone,
    I have a gridview with so many operations so i want to have above a searching for a specific operations i want to search by name or number so is searching bar or listbox will fit the search and i need the code too, please if anybody can help

    Thanks in advance.
    Thursday, August 2, 2018 1:58 AM

All replies

  • User283571144 posted

    Hi Omar27,

    According to your description, I suggest you could add a radio box list and textbox to achieve your requirement.

    In  the search button click event, you could get the select radio button value and search textbox value to query the database and generate the search result.

    More details, you could refer to below codes:

    <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="gridview.aspx.cs" Inherits="WebApplication.gridview" %>
     
    <!DOCTYPE html>
     
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
        <title></title>
    </head>
    <body>
        <form id="form1" runat="server">
            <table>
                <tr>
                    <td>
                        <asp:TextBox ID="txbData" runat="server"></asp:TextBox>
                        <asp:CheckBoxList ID="cblNames" runat="server" Visible="false" RepeatDirection="Horizontal"></asp:CheckBoxList>
                    </td>
                    <td>
                        <asp:RadioButtonList ID="rblCategory" runat="server" RepeatDirection="Horizontal" AutoPostBack="True" OnSelectedIndexChanged="rblCategory_SelectedIndexChanged">
                            <asp:ListItem Selected="True">ID</asp:ListItem>
                            <asp:ListItem>Name</asp:ListItem>
                            <asp:ListItem>Description</asp:ListItem>
                        </asp:RadioButtonList></td>
                    <td>
                        <asp:Button ID="btnSearch" runat="server" Text="Search" OnClick="btnSearch_Click" /></td>
                </tr>
                <tr>
                    <td colspan="3">
                        <asp:GridView ID="gvData" runat="server" AutoGenerateColumns="False" AutoGenerateEditButton="True" OnRowCancelingEdit="gvData_RowCancelingEdit" OnRowEditing="gvData_RowEditing" OnRowUpdating="gvData_RowUpdating" OnRowCommand="gvData_RowCommand" DataKeyNames="ID">
                            <Columns>
                                <asp:BoundField DataField="ID" HeaderText="ID" />
                                <asp:TemplateField HeaderText="Name">
                                    <ItemTemplate>
                                        <%# Eval("Name") %>
                                    </ItemTemplate>
                                    <EditItemTemplate>
                                        <asp:TextBox ID="txbName" runat="server" Text='<%# Bind("Name") %>'></asp:TextBox>
                                    </EditItemTemplate>
                                </asp:TemplateField>
                                <asp:TemplateField HeaderText="Video">
                                    <ItemTemplate>
                                        <%# Eval("Video") %>
                                    </ItemTemplate>
                                    <EditItemTemplate>
                                        <asp:Label ID="lblVideo" runat="server" Text='<%# Bind("Video") %>'></asp:Label>
                                        <asp:FileUpload ID="fuVideo" runat="server" /><asp:Button ID="btnVideo" runat="server" Text="Upload" CommandName="Upload" CommandArgument='<%# Bind("ID") %>' />
                                    </EditItemTemplate>
                                </asp:TemplateField>
                                <asp:TemplateField HeaderText="Description">
                                    <ItemTemplate>
                                        <%# Eval("Description") %>
                                    </ItemTemplate>
                                    <EditItemTemplate>
                                        <asp:TextBox ID="txbDescription" runat="server" Text='<%# Bind("Description") %>'></asp:TextBox>
                                    </EditItemTemplate>
                               </asp:TemplateField>
                            </Columns>
                        </asp:GridView>
                    </td>
                </tr>
            </table>
        </form>
    </body>
    </html>
    

    Code-behind:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.WebControls;
     
    namespace WebApplication
    {
        public partial class gridview : System.Web.UI.Page
        {
            Random random = new Random();
     
            string[] chars = new string[]
            {
                "A", "B", "C", "D", "E", "F", "G", "H", "J", "K",
                "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U",
                "V", "W", "X", "Y", "Z","a", "b", "c", "d", "e",
                "f", "g", "h", "i","j", "k",  "m", "n",  "p", "q",
                "r", "s", "t", "u", "v", "w", "x", "y", "z"
            };
     
            string[] names = new string[] { "Rico", "Brando", "Tom", "Jack", "Po", "Steve", "David" };
     
            // model
            private static List<GridViewEntity> source = new List<GridViewEntity>();
     
            protected void Page_Load(object sender, EventArgs e)
            {
                if (!IsPostBack)
                {
                    for (int i = 0; i < 30; i++)
                    {
                        GridViewEntity entity = new GridViewEntity();
                        entity.ID = i + 1;
                        entity.Name = this.GetNameByRandom();
                        entity.Description = this.GetStringByRandom(50);
                        source.Add(entity);
                    }
     
                    this.cblNames.DataSource = names;
                    this.cblNames.DataBind();
     
                    this.Bind();
                }
            }
     
            protected void gvData_RowEditing(object sender, GridViewEditEventArgs e)
            {
                GridView gv = (GridView)sender;
                gv.EditIndex = e.NewEditIndex;
                this.Bind();
            }
     
            // Cancel
            protected void gvData_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
            {
                GridView gv = (GridView)sender;
                gv.EditIndex = -1;
                this.Bind();
            }
     
            protected void gvData_RowUpdating(object sender, GridViewUpdateEventArgs e)
            {
                GridView gv = (GridView)sender;
                TextBox txbName = gv.Rows[e.RowIndex].FindControl("txbName") as TextBox;
                TextBox txbDescription = gv.Rows[e.RowIndex].FindControl("txbDescription") as TextBox;
                Label lblVideo = gv.Rows[e.RowIndex].FindControl("lblVideo") as Label;
     
                int id = Convert.ToInt32(gv.DataKeys[e.RowIndex].Value);
     
                GridViewEntity entity = source.Where(x => x.ID == id).Single();
                entity.Name = txbName.Text;
                entity.Description = txbDescription.Text;
                entity.Video = lblVideo.Text;
     
                gv.EditIndex = -1;
                this.Bind();
            }
     
            protected void gvData_RowCommand(object sender, GridViewCommandEventArgs e)
            {
                GridView gv = (GridView)sender;
     
                int index = Convert.ToInt32(e.CommandArgument) - 1;
     
                if (Equals(e.CommandName, "Upload"))
                {
                    FileUpload file = gv.Rows[index].FindControl("fuVideo") as FileUpload;
                    Label lblVideo = gv.Rows[index].FindControl("lblVideo") as Label;
     
                    // Omit upload code...
                    lblVideo.Text = random.Next(1000, 1000000).ToString();
                }
            }
     
            protected void rblCategory_SelectedIndexChanged(object sender, EventArgs e)
            {
               RadioButtonList rbl = (RadioButtonList)sender;
                this.txbData.Visible = rbl.SelectedValue != "Name";
                this.cblNames.Visible = !this.txbData.Visible;
            }
     
            protected void btnSearch_Click(object sender, EventArgs e)
            {
                IEnumerable<GridViewEntity> query = null;
     
                switch (this.rblCategory.SelectedValue)
                {
                    case "ID":
                        if (string.IsNullOrEmpty(this.txbData.Text)) { return; }
                        int id = Convert.ToInt32(this.txbData.Text);
                        query = source.Where(x => x.ID == id);
                        break;
                    case "Name":
                        string selectedNames = string.Empty;
                        foreach (ListItem item in this.cblNames.Items)
                        {
                            if (item.Selected)
                            {
                                selectedNames += string.Format("{0},", item.Value);
                            }
                        }
     
                        query = source.Where(x => selectedNames.Contains(x.Name));
                        break;
                    case "Description":
                        if (string.IsNullOrEmpty(this.txbData.Text)) { return; }
                        query = source.Where(x => x.Description.Contains(this.txbData.Text));
                        break;
                    default: break;
                }
     
                source = query.ToList();
     
                this.Bind();
            }
     
            private void Bind()
            {
                this.gvData.DataSource = source;
                this.gvData.DataBind();
            }
     
            private string GetStringByRandom(int length = 10)
            {
                StringBuilder builder = new StringBuilder();
                for (int i = 0; i < length; i++)
                {
                    builder.Append(chars[random.Next(0, 48)]);
                }
     
                return builder.ToString();
            }
     
            private string GetNameByRandom()
            {
                return names[random.Next(0, 6)];
            }
        }
    }
    

    Result:

    Best Regards,

    Brando

    Thursday, August 2, 2018 9:22 AM