how do i fill a datagridview with specific columns from sql

birddseedd

Member
Joined
Nov 18, 2008
Messages
6
Programming Experience
Beginner
My goal is too have a user chose a date with a date picker control, then the app will fill a data grid view with the "membername" and "present" columns for any row in the table in which the "date" column matches the date picker control.

This is the code im using to fill a datagridview with data from a sql table.

Dim sqlConn As New SqlConnection("connection string")
Dim sqlComm As New SqlCommand("SELECT * FROM memberlist", sqlConn)
Dim sqlAdptr As New SqlDataAdapter(sqlComm)
Dim ds As New DataSet
sqlAdptr.Fill(ds, "memberlist")
DataGridView1.DataSource = ds.Tables("memberlist")

This works; it is pulling 3 columns (date, membername, present). however...

I only want it to add the membername and present columns

Also I only want it to add data to the grid view for rows that have the same date as a date time picker in the form.


thanks for your help.
 
update:

It now only pulls from a certain date. however it still pulls all 3 columns

Dim myDate As Date = DateTimePicker1.Text
Dim sqlConn As New SqlConnection("server=.\SQLEXPRESS;Integrated Security=true; Database=memberlist;")
Dim sqlComm As New SqlCommand("SELECT * FROM memberlist where Date = @Date", sqlConn)
sqlComm.Parameters.AddWithValue("@Date", myDate)
Dim sqlAdptr As New SqlDataAdapter(sqlComm)
Dim ds As New DataTable
sqlAdptr.Fill(ds)
DataGridView1.DataSource = ds
sqlConn.Close()
 
Change the * in your SELECT statement to the columns you want returned, separated by a comma....

VB.NET:
Dim sqlComm As New SqlCommand("SELECT membername, present FROM memberlist where Date = @Date", sqlConn)
 
You should probably not go via the UI grid here, but instead just loop over the rows in the DataTable and send that back.
Sql commands other than SELECT is required to send data to database. It is usually more convenient to just use the data source wizard and have that generate the codes to interact with the database.
Here for example are introductions to these topics: Data Walkthroughs or video if you perfer Forms over Data Video Series
The UI parts is not needed specifically in this case, but it will give you everything else.
 
Back
Top