Displaying data in a datagridview

ralucutza77

New member
Joined
Feb 7, 2007
Messages
4
Programming Experience
Beginner
Hello,

I’m a begginer and I know that my question might sound stupid…So, what I’m trying to do, in a windows application, is connect to a SQL data base and display in a datagridview 4 columns from one table of that database. Well, my datagridview is empty and I don’t know what is the problem. What is the role of the BindingSource? Should I use it?

Here is the code:

Imports System.Data
Imports System.Data.SqlClient
Public Class Form1

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim myCon As New SqlConnection
Dim da As SqlDataAdapter
Dim ds As New DataSet
myCon.ConnectionString = "server = (local); database=Gigi;trusted_connection=true "
da = New SqlDataAdapter("select Date, TotalValue, Number, ID from bills", myCon)
myCon.Open()
da.Fill(ds)

Grid1.Columns.Add("Date", "Data factura")
Grid1.Columns.Add("Value", "Valoare totala")
Grid1.Columns.Add("Number", "Numar factura")
Grid1.Columns.Add("ID", "Serie factura")
Grid1.DataSource = ds.Tables(0).DefaultView

myCon.Close()



End Sub

Thanks!
 
Welcome to the forum :)

On a side note it saves the administrators hassle and work that when you post code, to paste your code between "code" and "/code" (replace the "" with [ ]) This then marks your post up correctly.

In terms of your question, have you tried using the data wizard? this will create your DataSet and DataTables for you - including the SQL and the connection required.
You can then drag and drop the DataTable onto a grid, this will bind it and set it all up automatically, and you can then use the display properties to select what columns you want visible.

Good luck with the app :)
 
Yes, I've used the wizard and it was ok, but now I'm trying to display the data without using it. Can you help, pls? Thanks.
 
Imports System.Data
Imports System.Data.SqlClient
VB.NET:
Public Class Form1

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim myCon As New SqlConnection
Dim da As SqlDataAdapter
Dim ds As New DataSet
myCon.ConnectionString = "server = (local); database=Gigi;trusted_connection=true "
da = New SqlDataAdapter("select Date, TotalValue, Number, ID from bills", myCon)
da.Fill(ds)
Grid1.DataSource = ds.Tables(0)

Here's a revised version of your code. There's no reason why it shouldn't work as long as there are rows being returned from the database. I removed the explicit opening and closing of the connection as the dataadapter handles this for you. Also i removed the manual adding of the columns as the dataadapter will also do this for you. Finally I removed the .defaultview from the setting of the datasource property. Try that if it still doesn't work i would look into whether or not rows are actually being returned from the database table.
 
Back
Top