[ASP.NET /VB.NET] P...
 
Notifications
Clear all

[ASP.NET /VB.NET] Populate a Datagrid view without a database


1UP
Posts: 25
 1UP
Topic starter
(@1UP)
Eminent RivalGamer
Joined: 9 years ago

I wanted to list out some data for a page that wasn't being pulled from a database but I didn't want to write out the table and all that. So I dropped a datagridview on to the webpage and wrote some code in the code behind.

ASP.NET Side of things

	  
	  
	
	  
	  
	
	  
	  
	

VB.Net Code

	
	  Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
	  PopulatePCGrid()
	
	  End Sub
	
	  Dim DT As New DataTable
	  Dim DR As DataRow
	
	  Private Sub PopulatePCGrid()
	  Dim DS As New DataSet
	
	  DT = New DataTable("items")
	  DT.Columns.Add("item1")
	  DT.Columns.Add("itemstat")
	  DR = DT.NewRow
	
	  AddRowToGrid("Operating System", My.Computer.Info.OSFullName.ToString)
	  DR = DT.NewRow
	  AddRowToGrid("Total Memory", ((My.Computer.Info.TotalPhysicalMemory / 1024) / 1024).ToString("N0") & " MB")
	
	  grd_Specs.DataSource = DT
	
	  grd_Specs.DataBind()
	  End Sub
	
	  Private Sub AddRowToGrid(ByVal description As String, ByVal data As Object)
	  With DR
	  .Item("item1") = description
	  .Item("itemstat") = data
	  End With
	  DT.Rows.Add(DR)
	  End Sub
	
	

I will explain this as best as I can.
We create two variables, 1 for the Data Table and 1 for the Data Row.
When we get into PopulatePCGrid we create a new data set and set up the data table to match the gridview layout. If these fields do not match you will get an error on page load. So make sure the fields you want exist in both the gridview and in the code behind.

I wrote a sub proceedure to add rows to the dataTable. This isn't required but it's best to break out code that you will be using over and over again and make them into functions /subs.

So we call the proceedure and pass in description and data. Data is an object simply because it could be anything. I didn't want to limit it to a string or integer because that wouldn't be true (and in fact on the actual page I wrote this for it wasn't true).

We then add that row to the data table and go back to PopulatePCGrid to finish the rest of the code. We create a new Datarow and then continue to add more information to the Data table. After we finish that we bind the datagridview and we end up with something like this:

Reply
Name of the Video Game, and any other Tags