Wednesday 1 April 2015

Simple selected fields in Gridview using c#

Here I am going to explain you, how to show only selected fields in Gridview using dropdown and command button

Here we go: Dropdown with field names

<asp:DropDownList ID="ddlsearch" runat="server" CssClass="selectpicker show-tick pull-right" data-live-search="true">
                        <asp:ListItem Text="Field 1" Value="Field 1"></asp:ListItem>
                        <asp:ListItem Text="Field 2" Value="Field 2"></asp:ListItem>                        
                    </asp:DropDownList>

<asp:Button ID="btnsf" runat="server" CssClass="btn btn-danger" Text="Search database" OnClick="btnsf_Click" />

C# CODE

string FieldName = Page.Request.Form["selectfields"].ToString();
        string[] SplitFieldName = FieldName.Split(',');

        if (FieldName.ToString() != "*")
        {
            if (SplitFieldName.Length < 11)
            {
                BindData();

                if (FieldName.IndexOf("Field 1") != -1) { gv.Columns[3].Visible = true; } else { gv.Columns[3].Visible = false; }
                if (FieldName.IndexOf("Field 2") != -1) { gv.Columns[5].Visible = true; } else { gv.Columns[5].Visible = false; }
                
            }
            else
            {
                string Alerts = "alert('Maximum fields can be select upto 10')";
                ScriptManager.RegisterClientScriptBlock((sender as Control), this.GetType(), "alert", Alerts, true);
                gv.DataBind();

            }

I HOPE THIS WILL HELP YOU, IF YOU HAVE ANY QUERY PLEASE REVERT.