none
Displaying and Sorting data in the DataGridView Control in VIsual Basic 2008

    Question

  • I've been asked by a local window cleaner to design a small utility that can display a grid of customer data, sort them, and then export it out as a formatted .txt or rtf file.

    The trouble is I don't have that much experience programming with the DataGridView control in Visual Basic 2008.

    It's not the exporting side of things I think I'll have trouble with. More of getting data into the DataGridView and making it sortable.

    I'd like the user to click an "Add" button on the main form of the program. Then display a new form which allows details to be inputted into text boxes. After clicking an OK button, I'd like a new row to be created on a DataGridView and displaying the inputted data in the appropriate columns.

    My first problem is that I can't figure out the best way of getting the data onto the DataGridView. I don't want to be messing with any SQL or databases, this program is only to be a utility so that the Window Cleaner can type up his daily round.

    My second problem is I don't know how to allow the sorting of the data, while keeping the structure of a "customer record" in tact. For example, Say I sort the price column into ascending order. I don't just want the prices to be sorted, I want the rest of the information of the appropriate customers to stay along side it.

    Any help on how to plan out this program, or what methods to use would be very much appreciated. Thank you :)
     

    Gknot
    Sunday, January 24, 2010 6:08 PM

Answers

  • first, you need to decide what columns you want.

    If it's for daily rounds for a window cleaner, I'll assume at minimum you want a Customer name, business location and "appointment" time

    since this is to be filled out daily, no need for a database, although one problem is if you fill it out in the morning and close the app, and then say an appointment is cancelled, you will no longer have the data to edit. In that case I would recommend saving the data in an XML file after the data is input in case you need to change it. But that can come later...

    the other thing is you don't need any special code to sort a datagridview - you can click on the column headers to sort that column. The only trick is the appointment time column, since to sort properly it needs to be a DateTime value type, but you only want to display the time portion of the DateTime.

    so to get you started try this in an app with 1 button, 2 textboxes, 1 datetimepicker and 1 datagridview. Enter a customer name in TextBox1, a business name in TextBox2 and a Time in the DateTimePicker, then click the button

    Worry about the printing, storing the daily data for editing and using a second form to input data until later. First get your DataTable/DataGridView set up properly first.

    Public Class Form1
        Dim dtTest As New DataTable("dtTest")
    
        Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
            dtTest.Columns.Add("Customer", GetType(String))
            dtTest.Columns.Add("Location", GetType(String))
            dtTest.Columns.Add("Appt_Time", GetType(DateTime))
            
            DataGridView1.DataSource = dtTest.DefaultView
            DataGridView1.Columns(2).DefaultCellStyle.Format = "h:mm tt"
            
            DateTimePicker1.Format = DateTimePickerFormat.Time
            DateTimePicker1.ShowUpDown = True
    
        End Sub
    
        Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
            If Not TextBox1.Text = String.Empty AndAlso Not TextBox2.Text = String.Empty _
                AndAlso Not DateTimePicker1.Value = Nothing Then
                dtTest.Rows.Add(TextBox1.Text, TextBox2.Text, DateTimePicker1.Value)
            End If
        End Sub
    End Class
    • Marked as answer by Kraig_Walker Tuesday, January 26, 2010 8:23 AM
    Monday, January 25, 2010 7:08 AM

All replies

  • Hello 

    @Giarknot

    First of all let me ask you, do you have any exp. with .net?  If not look at the top and you will see something like it LEARN. Click there please. 
    What you are after to, can be done. But I don't think User or people here in the forum will give you the information, if you know nothing about .net.

    what you are talking about is, adding a run time controls to your form. 

    I gonna give you e.g on how to load data to your DataGridview Control:

      Public Sub GetData()
            Dim connection As New SqlConnection(Write your connection string here please)
            Dim da As New SqlDataAdapter("SELECT * FROM Table_Inf", connection)
            Dim dt as New DataTable()
    da.Fill(dt)
            Me.DataGridView1.DataSource =   dt.DefaultView 
            connection.Close()
        End Sub




    Just Be Humble Malange!
    Sunday, January 24, 2010 8:07 PM
  • For you to sort your DataGridView I used MSDN e.g, I hope it helps you too...

    Private Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs) _
    Handles Button1.Click
        If RadioButton1.Checked = True Then
            DataGridView1.Sort(New RowComparer(SortOrder.Ascending))
        ElseIf RadioButton2.Checked = True Then
            DataGridView1.Sort(New RowComparer(SortOrder.Descending))
        End If
    End Sub
    
    Private Class RowComparer
        Implements System.Collections.IComparer
    
        Private sortOrderModifier As Integer = 1
    
        Public Sub New(ByVal sortOrder As SortOrder)
            If sortOrder = sortOrder.Descending Then
                sortOrderModifier = -1
            ElseIf sortOrder = sortOrder.Ascending Then
    
                sortOrderModifier = 1
            End If
        End Sub
    
        Public Function Compare(ByVal x As Object, ByVal y As Object) As Integer _
            Implements System.Collections.IComparer.Compare
    
            Dim DataGridViewRow1 As DataGridViewRow = CType(x, DataGridViewRow)
            Dim DataGridViewRow2 As DataGridViewRow = CType(y, DataGridViewRow)
    
            ' Try to sort based on the Last Name column.
            Dim CompareResult As Integer = System.String.Compare( _
                DataGridViewRow1.Cells(1).Value.ToString(), _
                DataGridViewRow2.Cells(1).Value.ToString())
    
            ' If the Last Names are equal, sort based on the First Name.
            If CompareResult = 0 Then
                CompareResult = System.String.Compare( _
                    DataGridViewRow1.Cells(0).Value.ToString(), _
                    DataGridViewRow2.Cells(0).Value.ToString())
            End If
            Return CompareResult * sortOrderModifier
        End Function
    End Class
    
    

    Just Be Humble Malange!
    Sunday, January 24, 2010 8:10 PM
  • Thanks for your help, but I'm not making much sense of the sql part. I do have experience with .NEt. But not the specific properties of getting the DataGridView control to work. I have seen that sort code before, thanks for that :)
    Gknot
    Sunday, January 24, 2010 9:19 PM
  • Couple of quick questions:

    Are you loading any data when you start the form, or will the utility always be empty when you start it?
    If you are loading data, are you loading from a database or a text file?  In other words what's the format of the data?
    Will you have to filter any of the data out?  Or just sort it?

    Malange's first post is assuming that you are loading data from a database.  If your data set is small, you could stay with flat text files, but this would get slow are you data set gets bigger.

    Even if you are using flat text files, there are ways to get Malange's code in his second post to work.

    -Hazelrah

    Monday, January 25, 2010 3:04 AM
  • You don't want to use a database, but Net has a disconnected approach, so you can benefit from those things which are made for a database.

    By instance a datatable, which in my idea perfectly fits to your purpose or a generic list.

    With both you can do everything you want about sorting searching hiding.

    The datatable is in fact a one to one representation of the data in the datagridview (that why it has its name) but a generic list is more from these days.

    For version 2010 which has automatic properties it would look with a list like this. (For orther versions you have to write something more for the properties)

    Public Class myClass
    Private Property CustomerName
    Private Property CustomerNumber
    End Class

    mc as new List(of myClass)
    dim bs as new bindingsource
    bs.DataSource =  mc
    dgv.DataSource = bs

     


    Success
    Cor
    Monday, January 25, 2010 5:28 AM
  • first, you need to decide what columns you want.

    If it's for daily rounds for a window cleaner, I'll assume at minimum you want a Customer name, business location and "appointment" time

    since this is to be filled out daily, no need for a database, although one problem is if you fill it out in the morning and close the app, and then say an appointment is cancelled, you will no longer have the data to edit. In that case I would recommend saving the data in an XML file after the data is input in case you need to change it. But that can come later...

    the other thing is you don't need any special code to sort a datagridview - you can click on the column headers to sort that column. The only trick is the appointment time column, since to sort properly it needs to be a DateTime value type, but you only want to display the time portion of the DateTime.

    so to get you started try this in an app with 1 button, 2 textboxes, 1 datetimepicker and 1 datagridview. Enter a customer name in TextBox1, a business name in TextBox2 and a Time in the DateTimePicker, then click the button

    Worry about the printing, storing the daily data for editing and using a second form to input data until later. First get your DataTable/DataGridView set up properly first.

    Public Class Form1
        Dim dtTest As New DataTable("dtTest")
    
        Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
            dtTest.Columns.Add("Customer", GetType(String))
            dtTest.Columns.Add("Location", GetType(String))
            dtTest.Columns.Add("Appt_Time", GetType(DateTime))
            
            DataGridView1.DataSource = dtTest.DefaultView
            DataGridView1.Columns(2).DefaultCellStyle.Format = "h:mm tt"
            
            DateTimePicker1.Format = DateTimePickerFormat.Time
            DateTimePicker1.ShowUpDown = True
    
        End Sub
    
        Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
            If Not TextBox1.Text = String.Empty AndAlso Not TextBox2.Text = String.Empty _
                AndAlso Not DateTimePicker1.Value = Nothing Then
                dtTest.Rows.Add(TextBox1.Text, TextBox2.Text, DateTimePicker1.Value)
            End If
        End Sub
    End Class
    • Marked as answer by Kraig_Walker Tuesday, January 26, 2010 8:23 AM
    Monday, January 25, 2010 7:08 AM
  • @Cor
    As far as I know, this could be done with MsFlexGrid in VBA, if i m not wrong. We can add data into MsFlexGrid table without any database connectivity, and then we can take out this data into something storage, could be text file.

    Is there any similarity with any data grid or something grid control in VB.NET can be used??

    It's too pity I don't have time to research this, but this case is very interesting me.

    My apologize if I get wrong with this MsFlexGrid. I can't remember what the grid name exactly. I had did this case when I was in college, using VBA :D
    Monday, January 25, 2010 9:12 AM
  • Harrie,

    The MSFlexGrid is a Com object which is not in use anymore in Net.

    Thousands including me have tried to use it in Net. It is something that makes you crazy.

    But the DataGridView comes the nearest to it, although the ListView does look in first view more to it.

    Removing the Row Header from the DataGridView has however almost the same effect.


    Success
    Cor
    Monday, January 25, 2010 11:23 AM
  • As far as I know, this could be done with MsFlexGrid in VBA, if i m not wrong. We can add data into MsFlexGrid table without any database connectivity, and then we can take out this data into something storage, could be text file.

    Is there any similarity with any data grid or something grid control in VB.NET can be used??




    While the DataGridView was designed very much with Data Binding in mind, there is no reason that you must used Data Binding.  In fact, you can set all of the columns up in the Designer before hand and load your data row by where ever your data comes from by using DataGridView.Rows.Add()

    You can also manually populate a DataTable in much the same fashion and bind that DataTable to the DataGridView.

    -Hazelrah
    Monday, January 25, 2010 11:33 AM
  • Couple of quick questions:

    Are you loading any data when you start the form, or will the utility always be empty when you start it?
    If you are loading data, are you loading from a database or a text file?  In other words what's the format of the data?
    Will you have to filter any of the data out?  Or just sort it?

    Malange's first post is assuming that you are loading data from a database.  If your data set is small, you could stay with flat text files, but this would get slow are you data set gets bigger.

    Even if you are using flat text files, there are ways to get Malange's code in his second post to work.

    -Hazelrah

    Oh sorry! I never pointed that. The program won't be loading in any pre-existing data from anywhere when it starts up.
    Gknot
    Monday, January 25, 2010 5:30 PM
  • Tes, that's a very good point. To those who posted some code up there (Thank's for your time on that by the way!) I'm giving it a shot right now.

    The trouble I find with leaving the default sorting, jwavila on the DataGridView is that it's only the data in that column that moves, thus muddling up the rest of the records. I wouldn't want that to happen now!

    Gknot
    Monday, January 25, 2010 5:36 PM
  • Uhhh...if you are not storing data in a databsae, what other data is there other than the data in the DataGridView ?

    You said muddling up the rest of the records - what records are those? The rest of the data in the DataGridView? Have you tried adding a few records in a DataGridView with multiple columns and sorting 1 of the columns?


    If you try the code I posted in a test app, I think you'll find when you sort 1 column, all the columns' data will stay "aligned"
    Monday, January 25, 2010 5:56 PM
  • Thank's jwavila! That's solved my problem!

    Now, I was wondering how to get the export of my program done. I'm pretty sure it's just to be exported as a .txt file or a .rtf

    (The chap, doesn't wants to fork out for excel or sign up for anything simpler, his knowledge of computing is quite limited, I think it's just becuase his hand writing is messy now)


    Gknot
    Monday, January 25, 2010 7:19 PM
  • you really should only ask 1 question per thread. Keeps the thread focused on one concept.

    You might want to close this thread as Answered by marking the post that answered populating and sorting the DataGridView as Answer, and any other posts that helped explain something as Helpful

    Then start a new thread with the next problem, if there is one. We also appreciate if, instead of an open ended question like "How do I do this?", if you try some code. If you can't get it to work, post the code that is causing the problem with a description of what you want it to do - and what it's doing wrong or not doing.

    Now you said you wanted to use a second Form to add the data to the DataGridView. Before you jump into printing finish off the adding data side of it. So you need to add a second Form to your app, then work on passing the data entered on that Form to the DataGridView on Form1.

    Monday, January 25, 2010 10:24 PM