Click here to Skip to main content
15,889,838 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
Hello My Dear Friends,

am facing problem with dropdown list , Please help

I will make you clear about the problem,

I have large number of data in my Database(sqlserver 2005) and on my webpage am using Gridview to display the data.... its fine. I have Dropdownlist beside gridview

when iam selecting " Sort by studentName" from dropdown list, it is displaying correctly on fist page of gridview, but in other pages it is not displaying in order wise.

So, my requirement is it should display in alphabetical order a-z. and also am using paging in gridview. WHEN I Select "sortby studentname" from dropdownlist it should display in alphabetical order for every page of gridview. when i clicks on paging.

and also i have another option from dropdown as "SORT BY DATE"
This is also should be same...when come to paging.

Please help, trying from 11 days. Please solve this and give me a good solution


this is my code
================

C#
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
    {

SqlConnection con = new SqlConnection(_connString);
        using (con)
        {
            con.Open();
            DataSet ds = new DataSet();
            if (DropDownList1.SelectedItem.Value == "Sort by StudentName")
            {
                SqlDataAdapter dad = new SqlDataAdapter("select RollNo, StudentId, StudentName, StudFatherName,DateLastChange, DateValidFrom,"
                    + "DateValidTo, ReservationNo, ClassType, location from StudentData order by StudentName", con);
                dad.Fill(ds, "records");
                GridView1.DataSource = ds.Tables[0];
                GridView1.DataBind();

            }

else if (DropDownList1.SelectedItem.Value == "Sort By Date")
            {


SqlDataAdapter dad = new SqlDataAdapter("select RollNo, StudentId, StudentName, StudFatherName,DateLastChange, DateValidFrom,"
                    + "DateValidTo, ReservationNo, ClassType, location from StudentData order by DateLastChange", con);
                
                dad.Fill(ds, "records");
                GridView1.DataSource = ds.Tables[0];
                GridView1.DataBind();

            }




THANKS IN ADVANCE.
Posted
Updated 17-Jul-12 2:05am
v3

You face this problem because, you are sorting your gridview on your dropdwon list selected index change event.

so when you using paging at that time in page index change event you are rebinding your gridview. am i right.?

so while you rebind your grid in page index change it will bind the grid with out sorting criteria. so you need to modify code for binding grid with sorted criteria in your page index change event.


so you can go like this.

1) create on function which will give you sort expression and store it in your view state or any thing else as per your requirement. As well as it will also maintain the sort direction, you can also maintain it with view state or other way.
2) so while binding grid you can use that view state value for sort expression as well as sort direction.
3) so while you fire your dropdown selected index change for sorting by student name then also set the value of view state for sort expression as student name and sort direction as asc or desc.
4) while you are going to change your page index as that time sort your data view using previously stored sort expression and direction to maintain sorting.

Instead of using order by cause in direct query you can use Default View of data-table and apply Sorting on that view, it is better idea for gridview sorting.

you can refer this links...
Sorting Gridview[^]
Sorting GridView 2[^]
 
Share this answer
 
v2
Try this :

You can use pageindexChanging event of Grid.
in that event you can write:

C#
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
   {
        GridView1.PageIndex = e.NewPageIndex;
SqlConnection con = new SqlConnection(_connString);
        using (con)
        {
            con.Open();
            DataSet ds = new DataSet();
            if (DropDownList1.SelectedItem.Value == "Sort by StudentName")
            {
                SqlDataAdapter dad = new SqlDataAdapter("select RollNo, StudentId, StudentName, StudFatherName,DateLastChange, DateValidFrom,"
                    + "DateValidTo, ReservationNo, ClassType, location from StudentData order by StudentName", con);
                dad.Fill(ds, "records");
                GridView1.DataSource = ds.Tables[0];
                GridView1.DataBind();
 
            }
 
else if (DropDownList1.SelectedItem.Value == "Sort By Date")
            {
 

SqlDataAdapter dad = new SqlDataAdapter("select RollNo, StudentId, StudentName, StudFatherName,DateLastChange, DateValidFrom,"
                    + "DateValidTo, ReservationNo, ClassType, location from StudentData order by DateLastChange", con);
                
                dad.Fill(ds, "records");
                GridView1.DataSource = ds.Tables[0];
                GridView1.DataBind();
           }


this will help you, if not please post it...
 
Share this answer
 
Comments
Software Engineer 892 17-Jul-12 5:00am    
Boss, it is not displaying alphabet wise in 2nd and other pages, only its displaying on first page of gridview when selected from dropdown. and i have take out Gridview1.databind from page indexing.....even its not working...PLEASE HELP.
Tejas Vaishnav 17-Jul-12 5:03am    
and what if any new filed for sorting. you can put that thing in your page index if else......

i don't think this is better idea. it will slow down the speed, instead of using direct database data you can simply sort it using data view sort property.
[no name] 17-Jul-12 5:22am    
if you want to display record alphabate wise you can use select query as Like 'alphabate%' in Grid.
Software Engineer 892 17-Jul-12 5:44am    
So, how to write a query to display the records alphabet wise(a-z)....Please help
Software Engineer 892 17-Jul-12 5:45am    
Query using sqlserver 2005
ASP.NET
<div>
            <asp:dropdownlist id="drp" runat="server" autopostback="true" onselectedindexchanged="drp_SelectedIndexChanged" xmlns:asp="#unknown">
                <asp:listitem text="orderid" value="1"></asp:listitem>
                <asp:listitem text="ContactName" value="2"></asp:listitem>
            </asp:dropdownlist>
        </div>
        <div id="my_box">
            <asp:gridview id="GridView1" runat="server" horizontalalign="Justify" autogeneratecolumns="False" xmlns:asp="#unknown">
                Width="100%" AllowPaging="True" PageSize="10" AllowSorting="True" OnPageIndexChanging="GridView1_PageIndexChanging"
                CssClass="mGrid" PagerStyle-CssClass="pgr" AlternatingRowStyle-CssClass="alt">
                <pagersettings position="TopAndBottom" firstpagetext="First" lastpagetext="Last">
                    NextPageText="Next" PreviousPageText="Previous" />
                <rowstyle horizontalalign="Center" verticalalign="Middle" font-names="Sans-Serif,Arial">
                    Font-Size="Small" />
                <columns>
                    <asp:boundfield datafield="OrderId" headertext="Job Ref" readonly="True" sortexpression="OrderId" />
                    <asp:boundfield datafield="Typeofwork" headertext="Language" readonly="True" sortexpression="Typeofwork" />
                    <asp:boundfield datafield="dateofmeeting" headertext="Job Date" readonly="True" sortexpression="dateofmeeting">
                        DataFormatString="{0:dd/MM/yyyy}" />
                    <asp:boundfield datafield="timeofmeeting" headertext="Job Time" readonly="True" sortexpression="timeofmeeting">
                        DataFormatString="{0:t}" />
                    <asp:boundfield datafield="Locationofmeeting" headertext="Location of Meeting" readonly="True">
                        SortExpression="Locationofmeeting" />
                    <%--<asp:boundfield datafield="Client(family)name" headertext="Client Name" readonly="True">
                        SortExpression="Client(family)name" />
                    <asp:boundfield datafield="ordertaken" headertext="Booking Submitted On" readonly="True">
                        SortExpression="ordertaken" DataFormatString="{0:dd/MM/yyyy HH:mm}" HtmlEncode="False">
                        <headerstyle horizontalalign="Left" />
                    </asp:boundfield>--%>
                    <asp:boundfield datafield="ContactName" headertext="Contact Name" readonly="True">
                        SortExpression="ContactName" />
                    <%--<asp:templatefield headertext="Interpreter Name" sortexpression="FirstName">
                        <edititemtemplate>
                            <asp:label id="Label1" runat="server" text="<%# Eval("InterpreterName") %>"></asp:label>
                        </edititemtemplate>
                        <itemtemplate>
                            <asp:label id="Label1" runat="server" text="<%# Bind("FirstName") %>"></asp:label>
                            <asp:label id="Label2" runat="server" text="<%# Eval("LastName") %>"></asp:label>
                        </itemtemplate>
                    </asp:templatefield>
                    <asp:templatefield headertext="Cancelled">
                        <itemtemplate>
                            <asp:label id="lblcancelled" runat="server" text="<%#Bind("Cancelled")%>"></asp:label>
                        </itemtemplate>
                    </asp:templatefield>
                    <asp:templatefield headertext="View">
                        <itemtemplate>
                            <asp:hyperlink id="ViewLink" runat="server" target="_self" text="View" navigateurl="<%# "Viewbooking.aspx?OrderId=" + DataBinder.Eval(Container, "DataItem.OrderId")%>">
                                ForeColor="Blue">
                            </asp:hyperlink>
                        </itemtemplate>
                    </asp:templatefield>--%>
                </asp:boundfield></asp:boundfield></asp:boundfield></asp:boundfield></asp:boundfield></columns>
                <pagerstyle cssclass="pgr" backcolor="Transparent" bordercolor="Transparent" font-underline="False" />
                <headerstyle font-bold="True" font-names="Sans-Serif,Arial" font-size="Small" forecolor="White">
                    Height="30px" HorizontalAlign="Left" BorderStyle="None" />
                <alternatingrowstyle cssclass="alt" />
            </headerstyle></rowstyle></pagersettings></asp:gridview>
        </div>


C#
using System;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class _Default : System.Web.UI.Page
{
    SqlConnection con = new SqlConnection(ConfigurationManager.AppSettings["Citas"]);
    SqlCommand cmd1 = new SqlCommand();
    public string custid;
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {

            bindgrid("orderid", "DESC");
        }

    }
    protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        GridView1.PageIndex = e.NewPageIndex;
        bindgrid(drp.SelectedItem.Text, null);

    }
    protected void drp_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (drp.SelectedItem.Text == "orderid")
        {
            bindgrid("orderid", "DESC"); 
        }
        else if (drp.SelectedItem.Text == "ContactName")
        {
            bindgrid("ContactName", "DESC"); 
        }
    }
    private void bindgrid(string sortExpression, string direction)
    {
        SqlDataAdapter da = new SqlDataAdapter("select top 100 * from Requests", con);
        DataTable dt = new DataTable();


        da.Fill(dt);
        DataView dv = new DataView(dt);
        if (IsPostBack)
        {
            dv.Sort = sortExpression + " " + direction;
        }


        GridView1.DataSource = dv;
        GridView1.DataBind();
        //DataSet ds = selectalljobsbydate(custid);
        //try
        //{
        //    GridView1.DataSource = dt;
        //    GridView1.DataBind();
        //}
        //catch (Exception ex)
        //{
        //    //lblMessage.Text = ex.Message;
        //    //lblMessage.ForeColor = Color.Red;
        //}
        //finally
        //{

        //    con.Close();
        //}

    }
}




hope it will work for you.....

kkakadiya....
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900