datagrid help

D0M1N8R

Member
Joined
Mar 14, 2007
Messages
11
Programming Experience
Beginner
Taking a VB.net class and a simple first project has been assigned to us.
The objective is to take a text file filled with comma separated values and display them fields as well as being able to sort them
I was looking through toolbox and seen the datagrid which looks like it may be a great solution for this project but am so far unable to figure out how to assign data programatically to each individual cell.
I have not been able to find any information on this so far and need some help. So here I am =)
Thanks
 
just done a quick search and because your textfile is comma seperated, you can use a OleDBOject to read the textfile and store in a DataTable instead a DataSet, and then you can bind your dataGrid to this.

Do a search on Google for "OleDBOject textfile DataSet" and you should find what you need.
 
D0M1N8R,
write a schema.ini (google it) for the text file
read the DW2 link in my signature, section "Fetching data into your application"
Except.. youre not using the Access driver, youre using the OLE Text File driver.. the rest of the instuctions should be the same
 
Thanks for the help guys. I'm getting stuck on the creation of a new data source step. I just not finding a option to use a OLE text file driver or anything similar. Maybe I've misunderstood you and shouldn't even be trying to create a new data source?
 
OK..

Open ODBC control panel
Add a User DSN
Text file driver
Choose the directory of the text file
Expand Options>>
Click Define Format
pick the txt file from the list on the left
Enter 25 in Rows To Scan
If your first line has col names, tick Col Name Header
Click Guess
Check what is has guessed
Say OK
Now your schema.ini has been written. Take a look in it..

I wrote one:
VB.NET:
[db.txt]
ColNameHeader=True
Format=CSVDelimited
MaxScanRows=0
CharacterSet=OEM
Col1=MY_LETTER_COL [B]Char[/B]
Col2=MY_NUMBER_COL Integer

Some bug in the control panel meant that the bold word Char in mine was missing. You might have to add it, if you experience a simialr thing

db.txt is my text file name. Now return to your VB 2005

Add a connection, Choose ODBC. Choose the DSN you made

Have a play!


Need a video of this? Just ask..
 
DOM1N8R:

I was just reading your posting and notice that you stated:
...a simple first project...
and
...take a text file filled with comma separated values and display them ...
and I really doubt that your instructor intended that you would use a DataGrid. That is a fairly advanced subject for a "first project."

And, the DataGrid is a terrible control, in my opinion, because it is what is called a "bound control" and bound controls are evil. You can use them without knowing how to really write proper code, but they will cause you a lot of headaches. Anyway, I'll save that for another time.

I think you should consider where you are in your book. What things have you covered so far. Probably Strings, Arrays, and things like that. Maybe also TextBoxes, ListBoxes and such. So If I was the one doing that project I would keep it in line with what I had already studied.

My instructions would read something like this:

OK, DOM, open a new VB.Net Windows Application (maybe name it FirstProject) and put a ListBox on the form. Make your ListBox about 2 inches across and maybe 4 inches high. Click on the TextBox to make sure it is selected and then you need to go to the Properties Window and name the ListBox MyListBox. Look down the list of Properties and find the Sorted Property and click on it. You will see a down arrow on the right and if you click on that you can change the Property to True. That is going to take care of the requirement
being able to sort them
Also, just kind of look through the various Properties available for the ListBox Control so you start to get familiar with them.

Next, put a Command Button on the form, maybe near the bottom of the form and in the center.

Now just click once on the Command Button and then go back to the Properties Window.

Near the top of the Properties Window you will find the Name Property for the Command Button. Name it cmdShow.

Next, go down almost to the bottom of the Properties Window and find the Text Property. Change the Text to something like Show Items.

Go back and just click somewhere on your form.

Since you are using a comma separated value file I assume that your instructor gave you that file.

I don't know where you have it on your computer, but it would be good to put it somewhere like in a file on your C drive named ProjectFiles or something like that, so you can easily write a path to the file.

Alright, back to your form. Double click on the Command Button and you will be taken to the code window and you will see the code for the click event of your button cmdShow and it will have something like:

PrivateSub cmdShow_Click(ByVal sender As System.Object, ByVal e .........
and then
EndSub

Next, take the following code and cut and paste it into your code window between PrivateSub and Endsub:
VB.NET:
Dim reader As IO.StreamReader
Dim inputLine As String
Dim fields() As String
reader = New IO.StreamReader("C:\TestFiles\CSVfile1.txt")
Do While reader.Peek() <> -1
inputLine = reader.ReadLine()
fields = inputLine.Split(","c) 
For Each field As String In fields
MyListBox.Items.Add(field)
Next
Loop
reader.Close()
reader = Nothing
In the code above, change the file path C:\TestFiles\CSVfile1.txt to whatever the path to your file is on your computer.

OK, click on the tab for your Form at the top of code window and you should be back at your form with the controls on it.

Now go to the menus at the top screen and click on Build, then Build Solution.

An Output Window should appear near the bottom of your screen and hopefully it will say something like:

Build: 1 succeeded, 0 failed, 0 skipped

If that is what it says, then you are good to go.

Oh, one thing before we do the final step. click once anywhere on your form and then go to the Properties Window. Go down toward the bottom and find the StartPosition Property and click on it and select CenterScreen. This will make your project appear in the center of the screen when it runs.

Alright, now for the final test. Go back to the menus at the top of the screen and click on Debug and then Start without Debugging, and keep your fingers crossed.

Your project should appear in the middle of your screen. Click on the Show Items button and you should see the items that were in your CSV file appear in the ListBox in alphabetical order.

Alright, I am almost done, but you have some work left to do.

I don't usually just do someone's homework projects for them, but I expect that you will now study that code and using your book to look up parts you don't understand, you will figure out just what it is doing and how it is doing it.

Good Luck and study hard.
 
bound controls are evil
How so? They embody the very essence of MVC architecture - a modern programming notion that fits particularly well with OO methodologies

You can use them without knowing how to really write proper code,
I most often hear this "proper code" argument from people whose code is, in my humble opinion, antiquated, inefficient and procedural in thought pattern.

While it might have been "proper code" in the '80s, things do move on..



they will cause you a lot of headaches
I reckon I could solve his homework question in about 2 minutes, with no headache.. Using bound controls. Manually bullying all the data into everything would take significantly longer, be significantly more messy, less well encapsulated and generally be less maintainable. It depends on the object lesson we are out to learn here. I'd prefer to learn concepts without getting bogged down in technicalities.


fields = inputLine.Split(","c)
Hopefully, this CSV doesnt contain any commas within fields. Parsing a CSV isnt a wheel you can re-invent with 2 lines of code, and parsers out there exist without having to write one's own. Microsoft have provided a way of reading a delimited file in using a VB function.. I forget what it is called.. JohnH knows.

Be careful, when launching into a big handhold of a post, that what you create will accurately satisfy the spec (that might not have been well told by the OP in the first place).. I personally agree with the OP's wish to use a
grid control.. your list isnt capable of representing 2D data, so fields cannot be individually sorted

I also have a library that performs sophisticated manipulation of data on the fly, that would be able to easily convert a CSV into the XML necessary for a dataset, but the code itself is so complex that the OP wouldnt have been able to write it, and it would stick out like a sore thumb to his tutor.. which is why I recommended a using-only-what-is-built-into-.net approach..
 
Microsoft have provided a way of reading a delimited file in using a VB function.. I forget what it is called.. JohnH knows.
That is the TextFieldParser class, new in .Net 2.0. Can be inserted in code with the Insert Snippet feature from FileIO section.
 
Thanks guys for the tips yet again. I've got the ODBC text driver working. Now its just a matter of pulling that data onto the data grid.
I did run into a few bugs or problems but got them sorted out..
Found out that the query tool doesnt like spaces
Ran into same Char missing at end of column names
The schema file built also inserted lines to other text files. Then the schema file appeared corrupted to the editor.
Long story short this has been a fun project. Learned a ton so far.
I'll be going through them links on your signature cjard but just wanted to update progress and let you know I really appreciate the help this far.
Thanks
 
Thanks guys for the tips yet again. I've got the ODBC text driver working. Now its just a matter of pulling that data onto the data grid.
I did run into a few bugs or problems but got them sorted out..
Found out that the query tool doesnt like spaces
Ran into same Char missing at end of column names
The schema file built also inserted lines to other text files. Then the schema file appeared corrupted to the editor.
Aye, its a pain in the arse sometimes.. If youre brave, you can write it by hand, with a google for schema.ini

Long story short this has been a fun project. Learned a ton so far.
I'll be going through them links on your signature cjard but just wanted to update progress and let you know I really appreciate the help this far.
Thanks

Just so you know, I've just quickly done a version for you:

I made a txt
Made a schema.ini
ODBC linked to it
Made a dataset from the ODBC
Dragged the grid to the form

I wonderd why nothing showed up, and eventually i realised that the DataMember of the BindingSource hadnt been set automatically. Strange, but setting it manually made everything work..

I also succeeded in doing the following two methods, which dont require a DSN:

Made a txt
Made a schema.ini (dont know if this is needed fopr this method)
Clicked Data Sources tab
Add Connection
Chose [Change]
Chose <other>
Chose Provider for OLEDB
OK
Chose Jet 4.0
Entered c:\temp\txtdb\ (the path where my txt is found) in file name
In advanced, typed the following in ExtendedProperties: text;HDR=Yes;FMT=Delimited
Click OK
ACCESS.c:\temp\txtdb\ appeared


Made a txt
Made a schema.ini (dont know if this is needed fopr this method)
Clicked Data Sources tab
Add Connection
Chose [Change]
Chose MS ODBC Data Source
OK
Use a connection string
Build
Picked the DSN i made earlier (note, it doesnt use the dsn, it copies the connection data out of it)
i.e. it put this (without spaces; the forum added those): Dsn=TextDB;dbq=C:\TEMP\TXTDB;defaultdir=C:\TEMP\TXTDB;driverid=27;fil=text;maxbuffersize=2048;pagetimeout=5

Click OK
ODBC.TEXT.c:\temp\txtdb\ appeared


Also if you have VB Express, you should be able to wangle this in via access:


Made a txt
Made a schema.ini (dont know if this is needed fopr this method)
Clicked Data Sources tab
Add Connection
Chose [Change]
Chose MS Access DB File
Entered c:\temp\txtdb\ (the path where my txt is found) in file name
In advanced, typed the following in ExtendedProperties: text;HDR=Yes;FMT=Delimited
Click OK
ACCESS.c:\temp\txtdb\ appeared



One of these ways will work to get you a connection to the text file...
 
reckon I could solve his homework question in about 2 minutes
Yes, I have seen some of those posting "hire Rent-A-Coder"

Bound controls have their place for quick and simple look-up features, but I don't think you will find that they are used very extensively in most larger applications. Could I be wrong about that?

Yes, I certainly could be, but most programmers I know would laugh at you if you gave them a project that used bound controls for anything except the most simple tasks.

Also, I would not write a program that required a DSN, because then you have to configure the same DSN on any computer you want to run the program on.

Does that make my way right and your way wrong. No, of course not. But, I think you would have to admit that using ADO.Net would make an application more efficient and much more scalable.

And, you may disagree with me, but that doesn't make you any more right or me any more right, it just means that we have different approaches to the problem and personally I think expressing different approches is good.

Apparently you felt I was making some personal attack on you, which was not my intent at all.

I was simply making a suggestion about how I felt the project should be approached.

He stated that this was a "first project" and, like I said, it is doubtful that a "first project" would be covering the DataGrid control. It is much more likely that the intent of the project was to teach something such as string manipulation in some manner.

Again, this was stated as being a "first project" and therefore I (possibly incorrectly) assumed that he was working with a simple comma separated list. If the list does contain something other than that then there woud have to be adjustments in the code to accomodate whatever that might be.

If I was his Instructor, I would be much more impressed with a student who solved a problem, or tried to solve a problem, based upon the material that had already been covered in the course, rather than using some approach that had not been covered.

Is my code perfect? Certainly not and it wasn't intended to be perfect. As I am sure you know, there are many ways that code could be written to perform that particular task.

Also, if you noticed, my code does not make any allowance for a line break or a carriage return.

All my code does, and all my code was intended to do, is to take a simple comma separated list and insert the words into a listbox. And, according to my reading of the original posting, that is all that was supposed to be done.

If I have a suggestion that I feel will help someone, I will feel free to post it and I would hope that you would feel free to post your suggestions and disagree with me.

Happy Computing! :) :) :)

 
Wow.. that's a long post! Some good points too :)


Data bound controls are used extensively where data manipulation is required. In MVC, the control has 2 very simple jobs: to show data found in a model, to change data within the model. Mostly, controls embody both, but you might also see a situation where a control edits the data and another shows it. While not a new concept, MVC is a modern one and makes for very efficient, scalable programs. Data is put in one place, the job of showing and manipulating it goes in another. This usually aligns very well with the concepts of abstraction and encapsulation, which are essential paradigms of OO. VB.NET is an OO language that just happens to use VB6-like syntax in order to garner market appeal; it is not an upgrade of VB6 and VB6 esque ways of doing things, such as storing data in controls, shouldnt be taught or used exclusively.

And now, for a story..

When I was at university, we had a brief in a competition, to demonstrate a prioritised queue structure, with enqueue and dequeue. The way of expressing this was through an air traffic control system; planes would be placed in a queue waiting to land/take of depending on what they were doing. Some keen students set to work right away. I didnt even feel like entering, but a day before a friend of mine said to me "so, are we gonna do this competition or what?"
After a game of Quake 3 we read the spec and knocked up something over a few hours that demonstrated the queues, planes arrived randomly as entries in a listbox, and progressed to the top where they landed/took off. The user could "inject" a plane to tes tthe queue prioritisation.
When we saw the competing entries we were rather embarassed at our efforts. One guy in paricular, had worked for days on an applet where the planes took off, flew over mountains, had coloured bars to represent how much fuel they had, they accelerated, turned and landed. He was rather gutted (and others surprised) when our entry won, for the simple reason that it covered the spec entirely, added nothing that was not asked for and met the requirements in a clear and concise way. Beautiful as though is air mapping system was, the guy who came in second had difficulty demonstrating exactly how a prioritised queue worked, which was the sole purpose of the spec.

What I took away from this (apart from some book tokens that I probably still have in a drawer) was that the spec is the bible. Complete the spec, nothing more, nothing less, and if its a rubbish spec, have it rewritten.
Typically the specs OPs give us on internet forums are not great and we have to imagine the details. However, the OP does imply that he needs his data representing in columns and be able to sort on those. This automatically excludes use of a list control (other than list view, which is a little antiquated) and virtually promotes use of a grid.. THough he is also not sure of exactly what he wants, the OP feels he wants to use a grid, which is also another indicator as to what he has been tasked to do.

I thoroughly appreciated what you were saying in your post, I was just a little concerned that it wouldnt meet the spec, maybe because you missed part of it (i miss things often, JohnH is usually the one to notice :D) or had some code lying around already that sort of did the job.. Of course youre free to post, and I know that you can accept I'm free to comment on your solution. I'm not actually a computer programmer, I'm a software engineer. It's not quite a poncy politically-correct title equivalent (ie stock replenishment executive vs shelfstacker) as they do have different roles, and the relevant courses of study diverge after a point.

I also agree with you that the DSN route is sub optimal, which is why i later expanded on it to include 3 ways of avoiding use of the DSN. I forgot, at the time, how to do it dsn-less. Oops :)

I'm not overjoyed at the exaltary titles the forum chooses to accord commensurate with post-count, but it's not something I can change here. On forums where I do have power to change it, i usually pick "Verbose Member" because on certain topics (data access is the current favourite because it is core to my current taskings) I usually have something to say.. (You;d never guess, right? ;))

It's good that you appreciate the spirit of open discussion; I know loads of people who havent and I do enjoy reading your psots; I'm hard to offend, and so far you havent done so, so do feel free to join in any future discussions, especially if you think I'm wrong or I've missed something! Welcome to the forums :D
 
Back
Top