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
eddyinperuAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

NunoGodinhoCommented:
Hi,

   you can do something like this:

    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

  This would solve your problem.

    Nuno Godinho
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
eddyinperuAuthor Commented:
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

0
eddyinperuAuthor Commented:
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
0
Cloud Class® Course: CompTIA Healthcare IT Tech

This course will help prep you to earn the CompTIA Healthcare IT Technician certification showing that you have the knowledge and skills needed to succeed in installing, managing, and troubleshooting IT systems in medical and clinical settings.

eddyinperuAuthor Commented:
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?
0
SKumar_1981Commented:
Try this

Private Sub lstSort_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles lstSort.SelectedIndexChanged
   
          Dim Source As DataView = DS.Tables("Authors").DefaultView
           
         Source.Sort = lstSort.SelectedValue.index
             dgADVTopics.DataSource = Source
             dgADVTopics.DataBind()
          End Sub
Regards,
skumar
0
deanvanrooyenCommented:
Here is an example of using the full constructor to create a view from the Customers Table in the Northwind Database such that it only contains customers from a specific region ( SP ) and country ( Brazil ), ####sorted by ContactName####, and including only current rows.

 

string connectionString = "..Nortwind Connection String..";
DataTable customers = new DataTable("Customers");

using (SqlConnection connection =  new SqlConnection(connectionString))
{
    SqlCommand selectAllCustomers = connection.CreateCommand();
    selectAllCustomers.CommandText = "SELECT * FROM [Customers]";

    connection.Open();
    customers.Load(selectAllCustomers.ExecuteReader(CommandBehavior.CloseConnection));
}

DataView dv = new DataView(customers,"Region = 'SP' and Country = 'Brazil'", "ContactName",DataViewRowState.CurrentRows);

dataGridView1.DataSource = dv;
0
NunoGodinhoCommented:
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
0
eddyinperuAuthor Commented:
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
0
deanvanrooyenCommented:


try


Dim Source As DataView = DS.Tables("Authors").DefaultView

 to this sort of thing (i use c# so change it to vb
Dim Source As DataView  = new DataView(DS.Tables("Authors"),"field = " + lstSort.SelectedValue , "orderbyvalue",DataViewRowState.CurrentRows);
0
eddyinperuAuthor Commented:
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
0
eddyinperuAuthor Commented:
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
0
eddyinperuAuthor Commented:
IS THERE NO EXPERTS THAT CAN HELP ME WITH THIS PROBLEM?

EDDY
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
ASP.NET

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.