By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
431,805 Members | 1,270 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 431,805 IT Pros & Developers. It's quick & easy.

Read CSV Files, then Display in Table format using variables

P: 14
I need to read and display data from a csv file in a table format. I then will need to use these data to calculate different values.
This is how the CSV file looks:
Expand|Select|Wrap|Line Numbers
  1. <table> <tr> <td>9 carat gold</td><td>11.87</td> </tr><tr> <td>18 carat gold</td><td>23.73</td> </tr><tr> <td>Silver</td><td>0.49</td> </tr><tr> <td>Platinum</td><td>27.52</td> </tr> </table>
I need to display these on a table format on the webpage (able to do that as gridview) then use individual values from the table to work out calculation i.e 10 grams of silver should be worked out by multiplying 0.49 (retrieved from the table) by 10.

That's the code I have so far for GridView:
Expand|Select|Wrap|Line Numbers
  1. If File.Exists("metals.csv") Then
  2.  Dim data As String() = File.ReadAllLines("metals.csv")
  3.  
  4.  Dim dt As New DataTable()
  5.  Dim col As String() = data(0).Split(",")
  6.  For Each s As String In col
  7.  
  8.  dt.Columns.Add(s, GetType(String))
  9.  
  10.  Next
  11.  For i As Integer = 0 To data.Length - 1
  12.  
  13.  Dim row As String() = data(i).Split(",")
  14.  
  15.  dt.Rows.Add(row)
  16.  
  17.  Next
  18.  
  19.  GridView1.DataSource = dt
  20.  
  21.  GridView1.DataBind()
  22.  End If
Is there another way of doing this say by using arrays to assign variables for each metal. I need to make sure they are displayed in a table format.

Thank you

Regards,
Mahmud
Jan 12 '15 #1
Share this Question
Share on Google+
17 Replies


Frinavale
Expert Mod 5K+
P: 9,731
The CSV file example you posted is not in Comma Separated Values (CSV) format.

If your file actually looks like what you posted you can simply use Response.Write to write the entirety of the file contents contents into the output stream and it will look like a table (because the file contains an HTML table).

Regardless of the fact that your file doesn't match the type that you are describing, what you are doing is fine: converting the file into an in-memory .NET data table and assigning it as the source of a GridView which displays as a table in the browser.

You an also bind the source of GridViews to sources that are not a DataTable type though.

For example, you can bind to a list or array of custom Metal objects if you would like.

Like, if you had the following custom Metal object:
Expand|Select|Wrap|Line Numbers
  1. Public Class Metal
  2.   Public Property Name As String
  3.   Public Property BasePriceInGrams As Double
  4.   Public Property AmountInGrams As Double
  5.  
  6.   Public Readonly Property Cost As Double
  7.     Get
  8.       Return BasePriceInGrams * AmountInGrams
  9.     End Get
  10.   End Property
  11.  
  12.   Public Sub New(ByVal metalName As String, ByVal basePrice As Double)
  13.     Me.Name = metalName
  14.     Me.BasePriceInGrams = basePrice
  15.     Me.AmountInGrams = 10 ' defaulting to 10 grams
  16.   End Sub
  17. End Class
You could read from the file and create Metal objects with the data that you retrieve to then set them as the source of your GridView.
Expand|Select|Wrap|Line Numbers
  1. ' ...code that you have for reading the file...
  2. ' But instead of using a DataTable as the source
  3. ' you can use a list of Metal objects
  4.  
  5. Dim metalsSource As New List(Of Metal)
  6.  
  7. For i As Integer = 0 To data.Length - 1
  8.  Dim data As String() = data(i).Split(",")
  9.  metalsSource.Add(New Metal(data(0), data(1))
  10. Next
  11.  
  12. GridView1.DataSource = metalsSource 
  13. GridView1.DataBind()
Now because the Metal object has additional properties (the Cost property in particular), you can bind to them in the UI/ASP markup for the GridView to display the "cost" of 10 grams for each metal.

-Frinny
Jan 12 '15 #2

P: 14
Bit confused with your model.
The data is in a CSV file I only made it into a table so you understand.
I have 2 CSV, first one should display the metal type and the price in pounds. These item should be shown in DataGrid.
The next CSV has rates in Euro and Dollar, I should use (read) the rates and use (multiply) by the pound rate value in the DataGrid column 2 and get a total value on column 3 & 4:

Expand|Select|Wrap|Line Numbers
  1. Imports System.IO
  2. Imports System.Data
  3.  
  4. Partial Class Precious
  5.     Inherits System.Web.UI.Page
  6.  
  7.  
  8.  
  9.     Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
  10.         If File.Exists("C:\Users\Mahmud\Documents\Visual Studio 2013\WebSites\WebSite2\metals.csv") Then
  11.             Dim data As String() = File.ReadAllLines("C:\Users\Mahmud\Documents\Visual Studio 2013\WebSites\WebSite2\metals.csv")
  12.  
  13.             If File.Exists("C:\Users\Mahmud\Documents\Visual Studio 2013\WebSites\WebSite2\rates.csv") Then
  14.                 Dim data2 As String() = File.ReadAllLines("C:\Users\Mahmud\Documents\Visual Studio 2013\WebSites\WebSite2\rates.csv")
  15.  
  16.                 Dim dt As New DataTable()
  17.                 Dim col As String() = data(0).Split(",")
  18.                 dt.Columns.Add("Metal Name")
  19.                 dt.Columns.Add("Rate in Pound")
  20.                 dt.Columns.Add("Rate in Euro")
  21.                 dt.Columns.Add("Rate in Dollar")
  22.  
  23.                 For Each s As String In col
  24.  
  25.                     dt.Columns.Add(s, GetType(String))
  26.  
  27.                 Next
  28.                 For i As Integer = 0 To data.Length - 1
  29.  
  30.                     Dim row As String() = data(i).Split(",")
  31.  
  32.                     dt.Rows.Add(row)
  33.  
  34.                 Next
  35.  
  36.                 GridView1.DataSource = dt
  37.  
  38.                 GridView1.DataBind()
  39.             End If
  40.  
  41.         End If
  42.     End Sub
  43. End Class
This is what I get so far:
Attached Images
File Type: jpg Table.jpg (22.3 KB, 168 views)
Jan 12 '15 #3

Frinavale
Expert Mod 5K+
P: 9,731
Like I said, there is nothing wrong with doing what you were originally... you asked for a different approach though.

What is confusing about the model?
The model class takes care of the calculations for you.
If you need to read from multiple files you can and then take the information that you gather from the files to populate the class with the data required to do the processing for you.

Then in the ASP markup code for the UI for the GridView you can bind to the properties or execute methods to do the calculations that you need to do to accomplish your task. If you don't use the model approach, it will still be a good idea to use the ASP markup for the GridView to do calculations during data binding.

-Frinny
Jan 13 '15 #4

P: 14
Sorry its a project for college, so a bit confused on what your trying to communicate.
The model is not doing any calculation at the moment, its just reading data from the CSV (metal) file.
I need to assign calculation on the Euro & Dollar column using the figures from the pound column and rates from the CSV file.
If you can direct me with some codes that will be great; all files are attached with the website I'm trying to create.

Thank you in advance
Regards
Attached Files
File Type: zip PreciousMetals_2015.zip (11.6 KB, 49 views)
Jan 13 '15 #5

Frinavale
Expert Mod 5K+
P: 9,731
In your course, have you learned about how the GridView can bind to Objects?

It takes all of the properties of the object and uses them as column headers by default.

This is why, in my demonstration Metal class, I added the ReadOnly Cost property.

It does calculations to display how much 10 grams of each metal would cost.

What you would do is add additional properties for currency conversions that you wish to display.

Check out the MSDN documentation for the GridView class

There you will find links to documentation for all of the GridView's properties, methods, and events along with additional articles that will show you how to use the control.

The MSDN Library contains this kind of documentation for all of the .NET controls available (some documentation is better than others and you may still need clarification after reading it)

Anyway, try my example in your code to see what it's like binding to the list of Objects instead of a DataTable.

Objects really do offer a lot more functionality :)




-Frinny
Jan 13 '15 #6

P: 14
Tried your code with the metal as object. Keep on getting errors:

Expand|Select|Wrap|Line Numbers
  1. Imports System.IO
  2. Imports System.Data
  3.  
  4. Public Class Metal
  5.     Inherits System.Web.UI.Page
  6.  
  7.     Public Property Name As String
  8.     Public Property BasePriceInGrams As Double
  9.     Public Property AmountInGrams As Double
  10.  
  11.     Public ReadOnly Property Cost As Double
  12.         Get
  13.             Return BasePriceInGrams * AmountInGrams
  14.         End Get
  15.     End Property
  16.  
  17.     Public Sub New(ByVal metalName As String, ByVal basePrice As Double)
  18.         Me.Name = metalName
  19.         Me.BasePriceInGrams = basePrice
  20.         Me.AmountInGrams = 10 ' defaulting to 10 grams
  21.  
  22.  
  23.     End Sub
  24.     Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
  25.  
  26.         If File.Exists("C:\Users\Mahmud\Documents\Visual Studio 2013\WebSites\WebSite2\metals.csv") Then
  27.             Dim data As String() = File.ReadAllLines("C:\Users\Mahmud\Documents\Visual Studio 2013\WebSites\WebSite2\metals.csv")
  28.  
  29.             If File.Exists("C:\Users\Mahmud\Documents\Visual Studio 2013\WebSites\WebSite2\rates.csv") Then
  30.                 Dim data2 As String() = File.ReadAllLines("C:\Users\Mahmud\Documents\Visual Studio 2013\WebSites\WebSite2\rates.csv")
  31.  
  32.  
  33.  
  34.                 Dim metalsSource As New List(Of Metal)
  35.                 For i As Integer = 0 To data.Length - 1
  36.                     data = data(i).Split(",")
  37.                     metalsSource.Add(New Metal(data(0), data(1)))
  38.  
  39.                 Next
  40.  
  41.                 GridView1.DataSource = metalsSource
  42.                 GridView1.DataBind()
  43.  
  44.             End If
  45.         End If
  46.     End Sub
  47.  
  48.  
  49. End Class
Is there another way of setting the column as object. The stuff you linked does not really give much info for this project.
Jan 13 '15 #7

Frinavale
Expert Mod 5K+
P: 9,731
Well, that's probably because you renamed your page to "Metal"....
The Metal class should not be your page class.

Change your class name back to the name of the page that the ASP code is expecting it to be and your errors will probably go away (in the future please post the error messages because otherwise people here have to guess what is going on) and remove the code that is supposed to be in the metal class out of your page code.

After you do that, add a new class to your project.
Call that class Metal.
Add the code for the metal class to the file you created.

-Frinny
Jan 14 '15 #8

P: 14
Done what you asked me to do.
an IndexoutOfRangeException is thrown on this code:
metalsSource.Add(New Metal(data(0), data(1)))

It seems metalsSource cannot retrieved the data. What else can be done
Jan 14 '15 #9

Frinavale
Expert Mod 5K+
P: 9,731
You need to make sure that the data array has at least 2 items in it. I assumed that it would always have 2 values...

Put a check in for the length of data before accessing indexes 0 and 1.

-Frinny
Jan 14 '15 #10

P: 14
Tried adding check for length but still the same issues as mentioned above arises:

Expand|Select|Wrap|Line Numbers
  1. If File.Exists("C:\Users\Mahmud\Documents\Visual Studio 2013\WebSites\WebSite2\metals.csv") Then
  2.             Dim data As String() = File.ReadAllLines("C:\Users\Mahmud\Documents\Visual Studio 2013\WebSites\WebSite2\metals.csv")
  3.  
  4.             If File.Exists("C:\Users\Mahmud\Documents\Visual Studio 2013\WebSites\WebSite2\rates.csv") Then
  5.                 Dim data2 As String() = File.ReadAllLines("C:\Users\Mahmud\Documents\Visual Studio 2013\WebSites\WebSite2\rates.csv")
  6.  
  7.                 Dim dt As New DataTable()
  8.  
  9.  
  10.  
  11.                 Dim metalsSource As New List(Of Metal)
  12.                 For i As Integer = 0 To data.Length - 1
  13.                     data = data(i).Split(",")
  14.                     Console.WriteLine(data.Length)
  15.                     metalsSource.Add(New Metal(data(0), data(1)))
  16.  
  17.                 Next
  18.  
  19.                 GridView1.DataSource = metalsSource
  20.                 GridView1.DataBind()
  21.             End If
  22.  
  23.         End If
Any other suggestions. Thank you so far for all your help
Jan 14 '15 #11

Frinavale
Expert Mod 5K+
P: 9,731
I'm not seeing the length checking.

Actually I see quite a few problems in the above code. Please see the comments in the following code:
Expand|Select|Wrap|Line Numbers
  1. 'The following line could cause a problem 
  2. 'if the file doesn't exist
  3. 'You are properly checking if it exists in the following line
  4. 'And after the following line you are populating
  5. 'a variable called "data2" with the lines
  6. '....you are using "data" to hold the strings
  7. ' that result from using the Split function on
  8. ' the lines from the file.
  9. 'I moved this into the appropriate place
  10.  
  11. 'Dim data As String() = File.ReadAllLines("C:\Users\Mahmud\Documents\Visual Studio 2013\WebSites\WebSite2\metals.csv")
  12.  
  13.  
  14.  
  15. 'In the line below: 
  16. '  consider using the Server.MapPath method to retrieve 
  17. '  the path to the file instead of hard coding the path because
  18. '  this won't work on a live server
  19.  
  20. If File.Exists("C:\Users\Mahmud\Documents\Visual Studio 2013\WebSites\WebSite2\rates.csv") Then
  21.  
  22.  ' data2 holds all of the lines from the file
  23.  ' you should be looping through this array 
  24.   Dim data2 As String() = File.ReadAllLines("C:\Users\Mahmud\Documents\Visual Studio 2013\WebSites\WebSite2\rates.csv")
  25.  
  26.  
  27.   'Dim dt As New DataTable() <- you don't need this if you are using the list
  28.  
  29.   Dim metalsSource As New List(Of Metal)
  30.   'You are using the same variable for too many things
  31.   'it is causing problems. 
  32.   'You should be looping through "data2" instead of data
  33.   'For i As Integer = 0 To data.Length - 1
  34.   '  data = data(i).Split(",")
  35.   '  'Console.WriteLine(data.Length) <- this makes no sense in an asp.net application
  36.   '  metalsSource.Add(New Metal(data(0), data(1)))
  37.   '
  38.   'Next
  39.  
  40.   'You should be looping through "data2" instead
  41.   For i As Integer = 0 To data2.Length - 1
  42.     Dim data = data2(i).Split(",")
  43.     If data.Length = 2 Then 'Right here is where you check the length of the data array before accessing the indexes!
  44.       metalsSource.Add(New Metal(data(0), data(1)))
  45.     End If
  46.   Next
  47.   ' You really should consider naming data2 something meaningful
  48.   ' consider renaming it to "linesFromFile" or something....
  49.  
  50.   'Likewise you should reconsider naming data to something meaningful
  51.   ' consider renaming it to "lineContents" or something
  52.  
  53.   GridView1.DataSource = metalsSource
  54.   GridView1.DataBind()
  55. End If

The following is the above posted code with no comments and properly named variables:
Expand|Select|Wrap|Line Numbers
  1.  
  2. If File.Exists(Server.MapPath("~/metals.csv")) Then 'Checking if the file exists before accessing it
  3.   'I'm not sure of your directory structure
  4.   'so you may need to replace the above and below Server.MapPaths with
  5.   'your hard coded value for now
  6.   'it was: File.Exists("C:\Users\Mahmud\Documents\Visual Studio 2013\WebSites\WebSite2\metals.csv")
  7.  
  8.   Dim fileLines As String() = File.ReadAllLines(Server.MapPath("~/metals.csv")) 'Retrieving all lines from file
  9.  
  10.   Dim metalsSource As New List(Of Metal) 'Will be used as the source for the GridView
  11.  
  12.   For i As Integer = 0 To fileLines.Length - 1 'Looping through the file lines to retrieve the content from them and populate the Metal objects with data
  13.     Dim lineContent As String() = fileLines(i).Split(",") 'Retrieving the content from the line 
  14.     If lineContent.Length = 2 Then 'Checking the length of the content to ensure that it is what we expect it to be before accessing the content to avoid errors/crashing
  15.       metalsSource.Add(New Metal(lineContent(0), Ctype(lineContent(1),Double))) 'Creating a new Metal object, populated with the data from the file, and adding it to the list which is the source for the grid
  16.     End If
  17.   Next
  18.  
  19.   GridView1.DataSource = metalsSource 'Setting the source of the GridView
  20.   GridView1.DataBind() 'Binding to the source
  21. End If
It just makes a lot more sense when variable names are meaningful.

-Frinny
Jan 15 '15 #12

P: 14
Now having issues with this line
Gridview1.Databind()

It throws an exception stating object reference not set to an instance.
Had to physically add in the path to the csv file instead of the servermap
Jan 16 '15 #13

Frinavale
Expert Mod 5K+
P: 9,731
Well I have no idea what you are doing to get a null reference exception if you have what I do. I don't know what your asp markup is for your page or what else you have in there that might be causing your null reference exception.

I don't usually do this because most people (including myself) either can't download sample projects or do not like to download attached example projects, but I have attached a sample project for you to grab.

Anyways, for those who cannot download the sample project I'm going to post the content of the project here.


This is the metals.csv file (located in the root of the project structure):
Expand|Select|Wrap|Line Numbers
  1. 9 carat gold,11.87
  2. 18 carat gold,23.73
  3. Silver,0.49
  4. Platinum,27.52
And this is the rates.csv file, also located in the root of my project structure:
Expand|Select|Wrap|Line Numbers
  1. USD,1.15325238
  2. EUR,1.4218
  3. GBP,1.80402381
(Please note that I am Canadian, so I am 'assuming' the base cost is in Canadian dollars and the other exchange rates are based off the exchange rate with the Canadian dollar as of end of day yesterday)


My Metal class is as follows:
Expand|Select|Wrap|Line Numbers
  1. Public Class Metal
  2.     Private _name As String
  3.     Private _basePriceInGrams As Double
  4.     Private _amountInGrams As Double
  5.  
  6.     Private _usdRate As Double
  7.     Private _euroRate As Double
  8.     Private _gbpRate As Double
  9.  
  10.     Public Property Name() As String
  11.         Get
  12.             Return _name
  13.         End Get
  14.         Set(ByVal value As String)
  15.             _name = value
  16.         End Set
  17.     End Property
  18.     Public Property BasePriceInGrams() As Double
  19.         Get
  20.             Return _basePriceInGrams
  21.         End Get
  22.         Set(ByVal value As Double)
  23.             _basePriceInGrams = value
  24.         End Set
  25.     End Property
  26.     Public Property AmountInGrams() As Double
  27.         Get
  28.             Return _amountInGrams
  29.         End Get
  30.         Set(ByVal value As Double)
  31.             _amountInGrams = value
  32.         End Set
  33.     End Property
  34.  
  35.     Public Property UsdRate() As Double
  36.         Get
  37.             Return _usdRate
  38.         End Get
  39.         Set(ByVal value As Double)
  40.             _usdRate = value
  41.         End Set
  42.     End Property
  43.     Public Property EuroRate() As Double
  44.         Get
  45.             Return _euroRate
  46.         End Get
  47.         Set(ByVal value As Double)
  48.             _euroRate = value
  49.         End Set
  50.     End Property
  51.     Public Property GBPRate() As Double
  52.         Get
  53.             Return _gbpRate
  54.         End Get
  55.         Set(ByVal value As Double)
  56.             _gbpRate = value
  57.         End Set
  58.     End Property
  59.  
  60.  
  61.     Public ReadOnly Property CanadianCost() As Double
  62.         Get
  63.             Return BasePriceInGrams * AmountInGrams
  64.         End Get
  65.     End Property
  66.     Public ReadOnly Property USACost() As Double
  67.         Get
  68.             Return BasePriceInGrams * AmountInGrams * UsdRate
  69.         End Get
  70.     End Property
  71.     Public ReadOnly Property EUROCost() As Double
  72.         Get
  73.             Return BasePriceInGrams * AmountInGrams * EuroRate
  74.         End Get
  75.     End Property
  76.     Public ReadOnly Property GBPCost() As Double
  77.         Get
  78.             Return BasePriceInGrams * AmountInGrams * GBPRate
  79.         End Get
  80.     End Property
  81.  
  82.  
  83.  
  84.     Public Sub New(ByVal metalName As String, ByVal basePrice As Double)
  85.         Me.Name = metalName
  86.         Me.BasePriceInGrams = basePrice
  87.         Me.AmountInGrams = 10 ' defaulting to 10 grams
  88.     End Sub
  89. End Class
Notice how my Metal class now has properties that let me get and set the exchange rates?

Notice how the Metal class also has properties that return the cost of each metal by using the exchange rates? These properties do all of the calculations so that the GridView can display them in the table.

Recall that the GridView, by default, will display all Public Properties as column headers in the table displayed on the screen. If you don't want something to display in the Grid (say what the exchange rates are) you have to do something to fix that.

Some options to only display the Properties that you want are to:
  • Change the scope of the property that you want to hide to "Friend" or "Private" but if you use private you will have to find a different way to set the values
  • Change the Properties in to methods (Subs/Functions) because methods are not displayed in grids
  • Not depend on the the default behaviour of the GridView and add the specific columns that you want to display

All of this information and MUCH more is in the links that I previously posted about the GridView control.


In my project, there is only one .aspx page in the project called "Default.aspx"

The following is the ASP markup for the Default.aspx file:
Expand|Select|Wrap|Line Numbers
  1. <%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default.aspx.vb" Inherits="_Default" %>
  2.  
  3. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  4. <html xmlns="http://www.w3.org/1999/xhtml">
  5. <head runat="server">
  6.     <title></title>
  7. </head>
  8. <body>
  9.     <form id="form1" runat="server">
  10.     <div>
  11.         <asp:GridView ID="GridView1" runat="server" />
  12.     </div>
  13.     </form>
  14. </body>
  15. </html>
And the following is the .vb server-side code for the Default.aspx.vb file:
Expand|Select|Wrap|Line Numbers
  1. Imports System
  2. Imports System.IO
  3. Imports System.Collections.Generic
  4.  
  5. Partial Class _Default
  6.     Inherits System.Web.UI.Page
  7.  
  8.     Protected Sub form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles form1.Load
  9.         Dim metalsSource As New List(Of Metal) 'Will be used as the source for the GridView
  10.  
  11.  
  12.         If File.Exists(Server.MapPath("~/metals.csv")) Then 'Checking if the file exists before accessing it
  13.             Dim metalsFileLines As String() = File.ReadAllLines(Server.MapPath("~/metals.csv")) 'Retrieving all lines from file
  14.             For i As Integer = 0 To metalsFileLines.Length - 1 'Looping through the file lines to retrieve the content from them and populate the Metal objects with data
  15.                 Dim metalLineContent As String() = metalaFileLines(i).Split(",") 'Retrieving the content from the line 
  16.                 If metalLineContent.Length = 2 Then 'Checking the length of the content to ensure that it is what we expect it to be before accessing the content to avoid errors/crashing
  17.                     metalsSource.Add(New Metal(metalLineContent(0), CType(metalLineContent(1), Double))) 'Creating a new Metal object, populated with the data from the file, and adding it to the list which is the source for the grid
  18.                 End If
  19.             Next
  20.         End If
  21.  
  22.         If File.Exists(Server.MapPath("~/rates.csv")) Then 'Checking if the file exists before accessing it
  23.             Dim exchangeRateFileLines As String() = File.ReadAllLines(Server.MapPath("~/rates.csv")) 'Retrieving all lines from file
  24.             For i As Integer = 0 To exchangeRateFileLines.Length - 1 'Looping through the file lines to retrieve the content from them and populate the Metal objects with data
  25.                 Dim exchangeRateLineContent As String() = exchangeRateFileLines(i).Split(",") 'Retrieving the content from the line 
  26.                 If exchangeRateLineContent.Length = 2 Then 'Checking the length of the content to ensure that it is what we expect it to be before accessing the content to avoid errors/crashing
  27.                     For Each m In metalsSource
  28.                         Select Case exchangeRateLineContent(0)
  29.                             Case "USD"
  30.                                 m.UsdRate = CType(exchangeRateLineContent(1), Double)
  31.                             Case "EUR"
  32.                                 m.EuroRate = CType(exchangeRateLineContent(1), Double)
  33.                             Case "GBP"
  34.                                 m.GBPRate = CType(exchangeRateLineContent(1), Double)
  35.                         End Select
  36.                     Next
  37.                 End If
  38.             Next
  39.         End If
  40.  
  41.         GridView1.DataSource = metalsSource 'Setting the source of the GridView
  42.         GridView1.DataBind() 'Binding to the source
  43.     End Sub
  44. End Class
Notice how I am creating Metal object instances based on what I retrieve from the metal.csv file.

Also notice how I am populating the Metal object instances with the exchange rates from the rates.csv file.


I have no errors when I run my code.

Usually the experts here will work with your current solution to find the best answers based on what you provide. Everyone's coding styles, concepts, approaches, and ways-of-thinking are different.


With that in mind, if you want to achieve the same thing using DataTables as an exercise we can look into what you would need to do to achieve that.

In particular, because DataTables do not have functionality that will do things like "apply an exchange rate", you would have to do the calculations when you retrieve the data from the files to store into the DataTable at the time of population... or you would have to change the GridView so that it does not use the default column-generation behaviour to create your own Template Columns that use ASP calls to do the calculations upon binding to the data to display it... or you would have to over write the row data binding events to do calculations at that point.


Once you try this out post back here and I will help you to understand anything that is confusing about it.

-Frinny
Attached Files
File Type: zip WebSite1.zip (4.3 KB, 57 views)
Jan 16 '15 #14

P: 14
Thank you very much for the code. Sorry been away from coding for a week concentrating on the theory aspect of the course.
The code works perfectly.
When it data binds it also displays the rates for each currency.
tried amending the code so the databind is not shown instead it just reads it and calculates EURO AND Dollar value. Is there a way of doing this?

Again thank you very much for showing me the rope.

Kind Regards
Jan 26 '15 #15

Frinavale
Expert Mod 5K+
P: 9,731
As I mentioned before, there are several options to only display the Properties that you want to:
  • Change the scope of the property that you want to hide to "Friend" or "Private" but if you use private you will have to find a different way to set the values
  • Change the Properties in to methods (Subs/Functions) because methods are not displayed in grids
  • Not depend on the the default behaviour of the GridView and add the specific columns that you want to display

The first (and easiest) thing I suggest you try is setting the properties in the Metal class for the Exchange Rates to Friend instead of Public.


-Frinny
Jan 27 '15 #16

P: 14
Thank you its functions.
I also databinded the name of each item to a dropdown list.
Expand|Select|Wrap|Line Numbers
  1.  DropDownList1.DataSource = metalsSource
  2.         DropDownList1.DataTextField = "Name"
  3.         DropDownList1.DataBind()
Now say if I choose Silver from the dropdown list, how will I display on a say textbox the price of Silver in one of the currency rate say in Euro or Dollar
As all data will be on a grid how do I get the row value for the silver from the different rates that's been calculated
Jan 30 '15 #17

Frinavale
Expert Mod 5K+
P: 9,731
Have you learned about the ASP.NET Page Life Cycle?

It is really important to understand this concept.

Right now the code we have is doing a data bind on controls the Page Load event but we should move that to the Page PreRender event to avoid losing information about what the user wants to do.

You can still create the metals data source in the Page Load event and you can still set the data source of your controls to the metals data source in that event...but you should hold off on calling DataBind until the PreRender event or else you could lose data that the user has indicated for editing purposes.


You need to implement a method that handles the DropDownList1's SelectedIndexChanged event. In that event you can retrieve the selected item based on the index provided and set the Text property of the text box to the value that you want to display.

Here is an example of a method that would handle the DropDownList1's SelectedIndexChanged event:

Expand|Select|Wrap|Line Numbers
  1. Sub DropDownList1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles DropDownList1.SelectedIndexChanged
  2.  
  3.    Dim selectedMetal = DropDownList1.SelectedItem
  4.  
  5.    ' you have the selected metal so you can now display what you want in a text box
  6.    ' if you have a text box called txt_metalPriceDetails on your page 
  7.    ' you would do the following
  8.  
  9.    txt_metalPriceDetails.Text = selectedMetal.EUROCost.ToString
  10.  
  11.  End Sub
-Frinny
Jan 30 '15 #18

Post your reply

Sign in to post your reply or Sign up for a free account.