Solved

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

Posted on 2006-07-21
12
415 Views
Last Modified: 2012-05-05
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
0
Comment
Question by:eddyinperu
  • 7
  • 2
  • 2
  • +1
12 Comments
 
LVL 6

Accepted Solution

by:
NunoGodinho earned 150 total points
ID: 17158462
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
 

Author Comment

by:eddyinperu
ID: 17158752
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
 

Author Comment

by:eddyinperu
ID: 17158785
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
 

Author Comment

by:eddyinperu
ID: 17158789
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
 
LVL 2

Assisted Solution

by:SKumar_1981
SKumar_1981 earned 100 total points
ID: 17158906
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
 
LVL 12

Assisted Solution

by:deanvanrooyen
deanvanrooyen earned 250 total points
ID: 17158959
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
Do You Know the 4 Main Threat Actor Types?

Do you know the main threat actor types? Most attackers fall into one of four categories, each with their own favored tactics, techniques, and procedures.

 
LVL 6

Expert Comment

by:NunoGodinho
ID: 17159863
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
 

Author Comment

by:eddyinperu
ID: 17163317
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
 
LVL 12

Assisted Solution

by:deanvanrooyen
deanvanrooyen earned 250 total points
ID: 17163954


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
 

Author Comment

by:eddyinperu
ID: 17164135
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
 

Author Comment

by:eddyinperu
ID: 17164801
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
 

Author Comment

by:eddyinperu
ID: 17173150
IS THERE NO EXPERTS THAT CAN HELP ME WITH THIS PROBLEM?

EDDY
0

Featured Post

Threat Intelligence Starter Resources

Integrating threat intelligence can be challenging, and not all companies are ready. These resources can help you build awareness and prepare for defense.

Join & Write a Comment

It was really hard time for me to get the understanding of Delegates in C#. I went through many websites and articles but I found them very clumsy. After going through those sites, I noted down the points in a easy way so here I am sharing that unde…
International Data Corporation (IDC) prognosticates that before the current the year gets over disbursing on IT framework products to be sent in cloud environs will be $37.1B.
Polish reports in Access so they look terrific. Take yourself to another level. Equations, Back Color, Alternate Back Color. Write easy VBA Code. Tighten space to use less pages. Launch report from a menu, considering criteria only when it is filled…
This video shows how to remove a single email address from the Outlook 2010 Auto Suggestion memory. NOTE: For Outlook 2016 and 2013 perform the exact same steps. Open a new email: Click the New email button in Outlook. Start typing the address: …

760 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

21 Experts available now in Live!

Get 1:1 Help Now