Link to home
Start Free TrialLog in
Avatar of eddyinperu
eddyinperu

asked on

I do not know how to sort a datagrid using a dropdownlist

I do not know if My last message was posted, my computer kick me out.
I have a dropdownlist(lstSort) and I want to be able to sort my datagrid depending of the value of my dropdownlist.
I have three value in my dropdownList(Name, Submit date ,Topic) I poblated my dropdownlist from ASP.
Andmy datagrid has 5 columns (First_name,Last_name,submit_date,Topic,Url) how can I sort the columns with the object dropdownlist?
Here is my code:

<form id="Form1" method="post" runat="server">
   <TBODY>
      <tr align="center">
                 <td style="HEIGHT: 52px" align="center">
                 <asp:label id="lblLink" runat="server" Font-Size="Small"  Width="179px">Click <a href="Submit.aspx" target="_self"><u>here</u></a> to submit.
                </asp:label>
<asp:label id="lblSort" runat="server" Font-Size="Small" Width="52px">Sort: </asp:label>

<asp:dropdownlist id="lstSort" runat="server">
<asp:ListItem Value="First_Name ASC">Name Asc</asp:ListItem>      
<asp:ListItem Value="Submit_DateTime ASC" Selected="True">DateTime ASC</asp:ListItem>      
<asp:ListItem Value="Topic ASC">Topic Asc</asp:ListItem>

</asp:dropdownlist>
      </tr>
      <tr>
      <td><asp:datagrid id=dgADVTopics runat="server"
                      Font-Size="10px"
            Width="476px"
            HorizontalAlign="Center"
            AlternatingItemStyle-BackColor="#abd6fe"
            HeaderStyle-BackColor="Desktop"
            HeaderStyle-VerticalAlign="Middle"
            HeaderStyle-BorderColor="white"
            HeaderStyle-BorderStyle="Double"
            HeaderStyle-ForeColor="white"
            HeaderStyle-HorizontalAlign="Center"
            CellPadding="5"
            DataSource="<%# dsADVTopics %>"
            BorderColor="#01305C"
            BackColor="Info"
            BorderStyle="Outset" Height="344px"
            PageSize="10"
            AllowPaging="True"
            PagerStyle-NextPageText="Next"
            PagerStyle-PrevPageText="Prev"
            OnPageIndexChanged="NewPage">
            <PagerStyle Font-Bold="True" HorizontalAlign="Right" ForeColor="Blue" Mode="NumericPages"></PagerStyle>
                                                            </asp:datagrid></td>
      </tr>
      <tr>
      </tr>
      </td>
      </tr>
      </FORM></table>



MY code of ASPX.vb :



    Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Try
            conString = "Network Library=DBMSSOCN;" & _
                        "Data Source=@@@@;" & _
                        "Initial Catalog=VB2;" & _
                        "User ID=sa;" & _
                        "Password=##"
              sqlCon = New SqlClient.SqlConnection(conString)
        Catch ex As Exception

            lblError.Visible = True
            lblError.Text = "Error connecting to the db." & vbCrLf & ex.ToString()
        End Try
        'get the data from the DB and display it in the datagrid
        Try
            daADVTopics = New SqlDataAdapter("SELECT First_Name + '' + Last_Name as Name, Submit_DateTime as [Date Submitted] , Topic, URL FROM ADVTopics ", sqlCon)
            daADVTopics.Fill(dsADVTopics, "ADVTopics")
            'dvADVTopics = dsADVTopics.Tables("ADVTopics").DefaultView
            dgADVTopics.DataSource = dsADVTopics
            dgADVTopics.DataBind()

        Catch ex As Exception
            lblError.Visible = True
            lblError.Text += "Error displaying information" & vbCrLf & ex.ToString()
        End Try
    End Sub

    Sub NewPage(ByVal sender As Object, ByVal e As DataGridPageChangedEventArgs)
        dgADVTopics.CurrentPageIndex = e.NewPageIndex
        dgADVTopics.DataBind()
    End Sub

    Private Sub lstSort_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles lstSort.SelectedIndexChanged
                          ' HOW CAN I DO THIS
    End Sub
I really will appreciate your help!!
THanks
ASKER CERTIFIED SOLUTION
Avatar of NunoGodinho
NunoGodinho

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of eddyinperu
eddyinperu

ASKER

Thanks,  NunoGodinho;  but I forget to tell you That My datagrid has been paging.
Sorting the column will mess up with the paging?

ALso; do you think that It is more easy to do it through my dataset instead of my dataview?
I will appreaciate your answer
Thanks
eddy

Hey  NunoGodinho , It did not work!
It doesn't want to accept the  symbol "   !=  "  from  " if (lstSort.SelectedIndex != -1)" , so I tried with the symbo '<>' but it didn't  work either.

I do not know if is reading  this function:

 Private Sub lstSort_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles lstSort.SelectedIndexChanged
   
         Dim dv as new DataView(dsADVTopics.Tables("ADVTopics"))

         if (lstSort.SelectedIndex != -1)
             dv.Sort = lstSort.SelectedValue
             dgADVTopics.DataSource = dv
             dgADVTopics.DataBind()
         end if
         

    End Sub


 By the way I am using VB.net and ASPX . thanks
Eddy
Another question more, sorry for bother you..... DO i need to create a function for the sort? if the answert is yes, how do i do that?
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Hi Eddy,

  I'm sorry about the '!=' but i normally work with c# and so you should use the '<>' symbol.

  The problem with the sorting and the pagging it's complicated to make the sort and stay in the same page that you were, and i think it doesn't make that mutch sense because if you sort the things you were seeing on the page will not be the same.

Hope it helped,

   Nuno Godinho
Hy deanvanrooyen  and SKumar_1981


I made this changes  to my code :                    " dgADVTopics.DataSource = Source "

It didn't work!  whyyyyyyyyyy yyy?     I am getting so mad with this problem!!

And   deanvanrooyen ,..I couldn't understand your answer, sorry about this , I recently started to study ASP and all these stuff, I apologize for my lack of knowledge refering to this subject. Could you be more specific about the connection? Because I don't think that I have a problem with my connection(my datagrid work great).  I want to work with a dataview and sort my datagrid with my dropdownlist(depending of the value that is inside the dropdownlist  'name', 'topic',sumitdat')
I want to fire the sort using the 'SelectedIndexChanged'  and if this doesn't work I will try to put a command button to make the sort. Could you use the example with the same variable that I wrote in my code? Thanks..!!

Do I need to write a function that sort?  how do I do this?

Thanks EXPERTS, I really appreciate your help
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
HI DEANVANROOYEN;

I try this:  



  Private Sub lstSort_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles lstSort.SelectedIndexChanged

        Dim Source As DataView = New DataView(dsADVTopics.Tables("ADVTopics"), "field = " + lstSort.SelectedValue, "orderbyvalue", DataViewRowState.CurrentRows)
        Source.Sort = lstSort.SelectedItem.Value
        dgADVTopics.DataSource = Source
        dgADVTopics.DataBind()
    End Sub


It didn't work!!!!!!!

This is the error:


Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.Data.DataException: DataTable must be set prior to using DataView.

Source Error:


Line 86:     Private Sub lstSort_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles lstSort.SelectedIndexChanged
Line 87:
Line 88:         Dim Source As DataView = New DataView(dsADVTopics.Tables("ADVTopics"), "field = " + lstSort.SelectedValue, "orderbyvalue", DataViewRowState.CurrentRows)
Line 89:         Source.Sort = lstSort.SelectedItem.Value
Line 90:         dgADVTopics.DataSource = Source
 

Thanksssss
Hey experts

I added a command button and I think it is workin but still I have a couple questions.
1) It sort my datagrid  depending of the value of my dropdownlist but I am using a  IF STATEMENT which allow me to decide for only 2 options , BUT I need three options(3 values in my dropdownlist ('name', 'SUbmit date', 'Topic') how can i do this?

2) I am paging my datagrid and when I am sorting a column and I go to the next page and that page is not excuting the sort that started in my first page

This is my code in VB.net i really do not know to much about C# :

Public Class WebForm2
    Inherits System.Web.UI.Page
    Dim sqlCon As SqlClient.SqlConnection
    Dim daADVTopics As SqlDataAdapter

    Protected WithEvents Form1 As System.Web.UI.HtmlControls.HtmlForm
    Protected WithEvents lblError As System.Web.UI.WebControls.Label
    Protected WithEvents lstSort As System.Web.UI.WebControls.DropDownList
    Protected WithEvents lblSort As System.Web.UI.WebControls.Label
    Protected WithEvents bttnSub As System.Web.UI.WebControls.Button
    Dim conString As String

#Region " Web Form Designer Generated Code "

    'This call is required by the Web Form Designer.
    <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()
        Me.dsADVTopics = New System.Data.DataSet
        Me.dvADVTopics = New System.Data.DataView
        CType(Me.dsADVTopics, System.ComponentModel.ISupportInitialize).BeginInit()
        CType(Me.dvADVTopics, System.ComponentModel.ISupportInitialize).BeginInit()
        '
        'dsADVTopics
        '
        Me.dsADVTopics.DataSetName = "NewDataSet"
        Me.dsADVTopics.Locale = New System.Globalization.CultureInfo("en-US")
        CType(Me.dsADVTopics, System.ComponentModel.ISupportInitialize).EndInit()
        CType(Me.dvADVTopics, System.ComponentModel.ISupportInitialize).EndInit()

    End Sub
    Protected WithEvents dsADVTopics As System.Data.DataSet
    Protected WithEvents dvADVTopics As System.Data.DataView
    Protected WithEvents dgADVTopics As System.Web.UI.WebControls.DataGrid
    Protected WithEvents lblLink As System.Web.UI.WebControls.Label

    'NOTE: The following placeholder declaration is required by the Web Form Designer.
    'Do not delete or move it.
    Private designerPlaceholderDeclaration As System.Object

    Private Sub Page_Init(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Init
        'CODEGEN: This method call is required by the Web Form Designer
        'Do not modify it using the code editor.
        InitializeComponent()
    End Sub

#End Region

    Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Try
            conString = "Network Library=DBMSSOCN;" & _
                        "Data Source=####;" & _
                        "Initial Catalog=VB2;" & _
                        "User ID=sa;" & _
                        "Password=???"

            sqlCon = New SqlClient.SqlConnection(conString)

        Catch ex As Exception

            lblError.Visible = True
            lblError.Text = "Error connecting to the db." & vbCrLf & ex.ToString()

        End Try

        Try
            daADVTopics = New SqlDataAdapter("SELECT First_Name + '' + Last_Name as Name, convert(varchar (10), Submit_DateTime,101) as [Date Submitted], Topic, URL FROM ADVTopics ", sqlCon)

            daADVTopics.Fill(dsADVTopics, "ADVTopics")

            dgADVTopics.DataSource = dsADVTopics
            dgADVTopics.DataBind()

        Catch ex As Exception
            lblError.Visible = True
            lblError.Text += "Error displaying information" & vbCrLf & ex.ToString()
        End Try
    End Sub

    Sub NewPage(ByVal sender As Object, ByVal e As DataGridPageChangedEventArgs)

        dgADVTopics.CurrentPageIndex = e.NewPageIndex
        dgADVTopics.DataBind()

    End Sub


    Private Sub bttnSub_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles bttnSub.Click

        dsADVTopics.Clear()

        dgADVTopics.Dispose()

        Try
            conString = "Network Library=DBMSSOCN;" & _
                        "Data Source=##" & _
                        "Initial Catalog=VB2;" & _
                        "User ID=sa;" & _
                        "Password=??"

            sqlCon = New SqlClient.SqlConnection(conString)
        Catch ex As Exception
            lblError.Visible = True
            lblError.Text = "Error connecting to the db." & vbCrLf & ex.ToString()
        End Try
        'refill the datagrid with the data sorted by the selected value in the list box
        Try
            If lstSort.SelectedItem.Text = "Name" Then
                daADVTopics = New SqlDataAdapter("SELECT First_Name + '' + Last_Name as Name,convert(varchar (10), Submit_DateTime,101) as [Date Submitted], Topic, URL from ADVTopics order by First_Name ASC", sqlCon)
            Else
                daADVTopics = New SqlDataAdapter("SELECT First_Name + '' + Last_Name as Name, convert(varchar (10), Submit_DateTime,101) as [Date Submitted], Topic, URL from ADVTopics order by Topic ASC", sqlCon)

            End If

            daADVTopics.Fill(dsADVTopics, "ADVTopics")
            dvADVTopics = dsADVTopics.Tables("ADVTopics").DefaultView
            dgADVTopics.DataSource = dvADVTopics
            dgADVTopics.DataBind()

        Catch ex As Exception
        End Try
    End Sub
IS THERE NO EXPERTS THAT CAN HELP ME WITH THIS PROBLEM?

EDDY