I've tried to add relation, to show the data on combobox and datagridview. I've tried this code below
Private Sub LoadSemester()
Me.OpenConn()
Dim dSet As New DataSet
Dim sql1 As String = "SELECT * FROM tbl_semester"
Dim comm1 As New SqlClient.SqlCommand(sql1, cnn)
Dim daSemester As SqlClient.SqlDataAdapter
Dim sql2 As String = "SELECT * FROM tbl_mk"
Dim comm2 As New SqlClient.SqlCommand(sql2, cnn)
Dim daMK As SqlClient.SqlDataAdapter
daMK = New SqlClient.SqlDataAdapter(comm2)
dSet.Clear()
daMK.Fill(dSet, "tbl_mk")
daSemester = New SqlClient.SqlDataAdapter(comm1)
dSet.Clear()
daSemester.Fill(dSet, "tbl_semester")
dSet.Relations.Add("relation", dSet.Tables("tbl_semester").Columns("id_pk"), dSet.Tables("tbl_pk").Columns("id_pk"))
With cmbSemester
.DataSource = dSet.Tables("tbl_semester")
.DisplayMember = "semester"
.ValueMember = "id_semester"
.SelectedIndex = 0
End With
'my datagridview here
End Sub
But it displayed nothing. But when I deleted the 'dSet.Relations.Add("relation", dSet.Tables("tbl_semester").Columns("id_pk"), dSet.Tables("tbl_pk").Columns("id_pk"))' the combobox showed the data.
I figured out maybe the problem is the dSet.Relation code. FYI, I am using SQLServer 2005 and VS Express 2012.
Related
I'm trying to synchronize the reading of a SQL Server table with 2 columns (nom_unité and cout_unité).
The first column (nom_unité) will be populated into a combobox and I want the second column (cout_unité) to be synchronized into a label with the first combobox (meaning, when I change the combobox value, the label should change too refering to the table).
I can do this with 2 comboboxes :
Dim connection As New SqlConnection("Data Source=xxx")
Dim dt As New DataTable
Dim sqlquery As String
connection.Open()
sqlquery = "select * from liste_unités"
Dim SQL As New SqlDataAdapter(sqlquery, connection)
SQL.Fill(dt)
Dim cmd As New SqlCommand(sqlquery, connection)
ComboBoxC1L1.DataSource = dt
ComboBoxC1L1.DisplayMember = "nom_unité"
ComboBox1.DataSource = dt
ComboBox1.DisplayMember = "cout_unité"
but I do not know how to do it with a label (instead of ComboBox1).
I believe I can achieve it with something like that :
Dim sqlcmd As New SqlCommand("select * from liste_unités", connection)
Dim myreader As SqlDataReader
myreader = sqlcmd.ExecuteReader()
myreader.Read()
If myreader.HasRows Then
Label1.Text = myreader.Item("cout_unité").ToString
End If
but this is only reading the first row and not changing the label value when changing the first combobox selected value.
How to do it the easiest and most efficient way ?
Thank you :)
As you have assigned the datasource of the combobox to a datatable which contains the information you need, you can get that information when the value of the combobox changes.
I started a new Windows Forms project and put a combobox (named "cbNomUnité") and a label (named "lblCoutUnité") on Form1 and used this code:
Imports System.Data.SqlClient
Public Class Form1
Dim connStr As String = "Server=.\SQLEXPRESS;Database=Testing;Trusted_Connection=true;"
Sub PopulateCB()
Dim sql = "SELECT nom_unité, cout_unité FROM liste_unités"
Dim dt As New DataTable
Using conn As New SqlConnection(connStr),
da As New SqlDataAdapter(sql, conn)
da.Fill(dt)
End Using
cbNomUnité.DataSource = dt
cbNomUnité.DisplayMember = "nom_unité"
End Sub
Private Sub ComboBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cbNomUnité.SelectedIndexChanged
Dim cb = DirectCast(sender, ComboBox)
If cb.SelectedIndex >= 0 Then
Dim val = DirectCast(cb.SelectedItem, DataRowView).Row.Field(Of String)("cout_unité")
lblCoutUnité.Text = val
End If
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
PopulateCB()
End Sub
End Class
To get a program that does this:
(Refresh the page to see the animation again.)
I am using SQL Server 2016 Visual studio 2017.
Need to fill checkedlistbox2, from my database, based on the value of the SelectedItem of Checkedlistbox1.
I am filling checkedlistbox1 on Form.Load as below:
This code is working.
Private Sub fillChkboxList()
Dim conn As New SqlConnection("Data Source=192.168.200.36;user id=sa;password=XXXX#123;database=XXXXXXX")
Dim sda As New SqlDataAdapter("select DepartmentName, DepartmentID from DepartmentMain where active=1 order by DepartmentName", conn)
Dim dt As New DataTable
sda.Fill(dt)
CheckedListBox1.DataSource = dt
CheckedListBox1.DisplayMember = "DepartmentName"
CheckedListBox1.ValueMember = "DepartmentID"
End Sub
Here I am trying to use a method to fill Checkedlistbox2, which I am calling in the ItemCheck event handler of Checkedlistbox1:
Below Code is not giving required results
Public Function fillChkboxListSub()
Dim i As Integer
Dim conn1 As New SqlConnection("Data Source=192.168.200.36;user id=sa;password=XXXX#123;database=XXXXXXX")
With CheckedListBox2
For i = 0 To CheckedListBox1.Items.Count - 1 Step i + 1
If CheckedListBox1.GetItemCheckState(i) = CheckState.Checked Then
Dim xx As String = (CType(CheckedListBox1.Items(i), DataRowView))("DepartmentID")
Dim sqlstr2 As String = "select SubName,SubDeptID from DepartmentSub where active=1 and DepartmentID in ('" & xx & "') order by SubName"
Dim command2 As New SqlCommand(sqlstr2, conn1)
Dim adpt2 As New SqlDataAdapter(command2)
adpt2.SelectCommand = command2
adpt2.Fill(dt2)
CheckedListBox2.DataSource = dt2
CheckedListBox2.DisplayMember = "SubName"
CheckedListBox2.ValueMember = "SubDeptID"
End If
Next
End With
End Function
This function I am calling on:
Private Sub CheckedListBox1_ItemCheck(sender As Object, e As ItemCheckEventArgs) Handles CheckedListBox1.ItemCheck
fillChkboxListSub()
End Sub
I am not getting the result.
If I check the (DepartmentName) in checkedlistbox1, SubDeptName should load in checkedlistbox2. If I deselect the same in checkedlistbox1, it should be deleted or removed from checkedlistbox2Please help with working code example.
Thanks in Advance
Most database objects need to be disposed. Connections, Commands, and DataReaders have a Dispose method that must be called to release unmanaged resources that they use. It is made easy for us with Using...End Using blocks that ensure that Dispose is called even if there is an error.
The order of setting the DataSource, DisplayMember, and ValueMember is important. Setting DataSource should be last line. If you set ValueMember before DataSource no action is triggered. If you set Datasource first, the box will bind value member for you. Then, you're going to set a new ValueMember (the one you want) and box will have to re-wire binding. So, if you set DataSource last, bindings will happen only once.
You can use the CheckedItems collection to loop through. Add eacn item to a list. After the loop use Join with a comma separator to prepare the In clause for the sql string. I used an interpolated string to build the sql string indicated by the preceding $. Variables can then be inserted in line surrounded by { } .
Private CnString As String = "Data Source=192.168.200.36;user id=sa;password=XXXX#123;database=XXXXXXX"
Private Sub fillChkboxList1()
Dim dt As New DataTable
Using conn As New SqlConnection(CnString),
cmd As New SqlCommand("select DepartmentName, DepartmentID from DepartmentMain where active=1 order by DepartmentName", conn)
conn.Open()
Using reader = cmd.ExecuteReader
dt.Load(reader)
End Using
End Using
CheckedListBox1.DisplayMember = "DepartmentName"
CheckedListBox1.ValueMember = "DepartmentID"
CheckedListBox1.DataSource = dt
End Sub
Public Sub fillChkboxList2()
Dim lst As New List(Of Integer)
For Each item In CheckedListBox1.CheckedItems
Dim drv = DirectCast(item, DataRowView)
Dim DepId As Integer = CInt(drv("DepartmentId"))
lst.Add(DepId)
Next
Dim DepIdString = String.Join(",", lst)
Dim sql As String = $"select SubName,SubDeptID from DepartmentSub where active=1 and DepartmentID in ({DepIdString}) order by SubName"
Debug.Print(sql) 'See if your select string looks correct.
Dim dt As New DataTable
Using cn As New SqlConnection(CnString),
cmd As New SqlCommand(sql, cn)
cn.Open()
Using reader = cmd.ExecuteReader
dt.Load(reader)
End Using
End Using
CheckedListBox2.DisplayMember = "SubName"
CheckedListBox2.ValueMember = "SubDeptID"
CheckedListBox2.DataSource = dt
End Sub
I want to pull image data from SQL Server 2008 Express and display it directly in a Crystal Report. I am using Visual Studio 2012 along with Crystal Reports for Visual Studio (also a full version of SAP Crystal Reports 2013).
I have attempted to use samples from Google/SO searches but I seem to be missing at least one key element. In my project I have a dataset with one field which is of System.Byte(), a Crystal Report, and a viewer.
Here is the snippet of code which queries the database, reads the memorystream, and puts the image data into the dataset.
Dim ds As New DataSet1
Dim row As DataRow
Dim objConn As New SqlConnection(DatabaseConnection.CTLDataConnectionString)
Dim objCommand As SqlCommand = objConn.CreateCommand
objCommand.CommandText = "SELECT Content FROM Report WHERE HandlingUnitID = " & HandlingUID
Dim dr As SqlDataReader = Nothing
If objConn.State = ConnectionState.Closed Then objConn.Open()
dr = objCommand.ExecuteReader
If dr.HasRows Then
dr.Read()
Dim b() As Byte = DirectCast(dr("Content"), Byte())
Using ms As New MemoryStream(b)
ds.DataTable1.Rows.Add(b)
End Using
End If
Dim rpt As New ShipLabel
rpt.SetDataSource(ds.Tables("DataTable1"))
Dim frm As New CRviewer
frm.CRvwr.ReportSource = rpt
frm.ShowDialog()
This will bring up the Crystal Viewer but it is a blank report. I want to know if I have the correct sequence for getting the data, and if I am storing it correctly in the dataset.
After a lot more reading/researching I have the following snippets of code which appear to have the correct sequencing, and correctly storing the data in the dataset. This snippet is from a cellclick event.
Dim ds As New DataSet1
Dim row As DataRow
Dim img As Bitmap
Dim objConn As New SqlConnection(DatabaseConnection.CTLDataConnectionString)
Dim objCommand As SqlCommand = objConn.CreateCommand
objCommand.CommandText = "SELECT Content FROM Report WHERE HandlingUnitID = " & HandlingUID
Dim dr As SqlDataReader = Nothing
If objConn.State = ConnectionState.Closed Then objConn.Open()
dr = objCommand.ExecuteReader
If dr.HasRows Then
dr.Read()
Dim b() As Byte = dr("Content")
Using ms As New MemoryStream(b)
img = Image.FromStream(ms)
b = ConvertImageToByte(img)
ds.DataTable1.Rows.Add(b)
End Using
End If
objConn.Close()
Dim rpt As New ShipLabel
rpt.SetDataSource(ds.Tables("DataTable1"))
rpt.SetParameterValue("JobNumber", OrderNumber.ToString)
Dim frm As New CRviewer
frm.CRvwr.ReportSource = rpt
frm.ShowDialog()
And this function:
Public Shared Function ConvertImageToByte(ByVal Value As Image) As Byte()
If Value IsNot Nothing Then
Dim fs As MemoryStream = New MemoryStream()
CType(Value, Bitmap).Save(fs, ImageFormat.Jpeg)
Dim retval As Byte() = fs.ToArray()
fs.Dispose()
Return retval
End If
Return Nothing
End Function
This issue is driving me mad, I can't work out why it's happening. I'm running a query in an access db using vb.net then putting the data into a listview. Code:
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim strAccessConn As String = "Provider = Microsoft.ACE.OLEDB.12.0; Data Source = T:\mydb.accdb"
Dim cn As OleDbConnection = New OleDbConnection(strAccessConn)
Dim ds As New DataSet
Dim dt As DataTable
'Note the query is entered as a string.
Dim da As New OleDbDataAdapter("Q_LIST", cn) 'is the name of the query in Access
'Set the CommandType of the SelectCommand to TableDirect
da.SelectCommand.CommandType = CommandType.TableDirect
da.Fill(ds, "mytable")
dt = ds.Tables("mytable")
ListViewBatchResults.MultiSelect = True
ListViewBatchResults.View = View.Details
ListViewBatchResults.GridLines = True
ListViewBatchResults.Columns.Clear()
ListViewBatchResults.Items.Clear()
For Each col As DataColumn In dt.Columns()
ListViewBatchResults.Columns.Add(col.ToString)
Next
MsgBox(dt.Rows.Count)
For Each row As DataRow In dt.Rows()
Dim lst As ListViewItem
lst = ListViewBatchResults.Items.Add(row(0))
For i As Integer = 1 To dt.Columns.Count - 1
lst.SubItems.Add(row(i))
Next
Next
End Sub
This listview is not showing all the returned data though, and I can't work out why - it works on other queries in the DB but not this one for some reason. The row count shows that there are 264 rows, the listview only shows 3 of them when I run the project however. What the heck is going on?
Cheers!
Dim lst As ListViewItem
to
Dim lst As New ListViewItem
I have a SQL Server Compact database created through VS 2010 (Local Database File option).
On form load (CategoryForm) I load the values from the database into the DataGridView1. I also add an extra ButtonColumn programmatically that I use for the Delete part.
The problem is this:
On initial form load, the first time I press delete on any row, it works. If i press it again it does not work.
The second time i click the button, the printed text I get on my Msgbox, is the Text of button! (delete) (screenshot included) p.s As mentionted below, when I comment-out the extra stuff, I get the correct values returned.
What I tried:
Commented out everything SQL-related, left only the part where I get the RowIndex and the value at the specific cell at that index. I print them both on MsgBox. The values I get are correct. For example, 0 index and value test for first row with text test.
Below is my progress as well as screenshots:
CellContentClick method:
Private Sub DataGridView1_CellContectClick(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DataGridView1.CellContentClick
Dim i As String
'If e.ColumnIndex = 1 Then
'If e.RowIndex >= 0 And e.RowIndex <= DataGridView1.Rows.Count - 1 Then
i = DataGridView1.Rows(e.RowIndex).Cells(0).Value.ToString
MsgBox(e.RowIndex)
MsgBox(i)
SQLStringDelete = "DELETE FROM Category WHERE categoryname = '" & i & "'"
SQLConn.ConnectionString = ConnString 'Set the Connection String
SQLConn.Open() 'Open the connection
SQLCmd.Connection = SQLConn 'Sets the Connection to use with the SQL Command
SQLCmd.CommandText = SQLStringDelete 'Sets the SQL String
SQLCmd.ExecuteNonQuery() 'Executes SQL Command
'Create Adapter
Dim DataAdapter As SqlCeDataAdapter = New SqlCeDataAdapter("SELECT categoryname FROM Category", SQLConn)
'Create DataSet
Dim Dataset As New DataSet
'fill the datset
DataAdapter.Fill(Dataset)
'attach dataset to the datagrid
With DataGridView1
.DataSource = Dataset.Tables(0)
.Columns(0).HeaderText = ""
.Columns(0).AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill
End With
DataAdapter = Nothing
Dataset = Nothing
SQLConn.Close() 'Close the connection
End Sub
Form_Load method:
Private Sub CategoryForm_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
SQLConn.ConnectionString = ConnString 'Set the Connection String
SQLConn.Open() 'Open the connection
'Create Adapter
Dim DataAdapter As SqlCeDataAdapter = New SqlCeDataAdapter("SELECT categoryname FROM Category", SQLConn)
'Create DataSet
Dim Dataset As New DataSet
'fill the datset
DataAdapter.Fill(Dataset)
'attach dataset to the datagrid
With DataGridView1
.DataSource = Dataset.Tables(0)
.Columns(0).HeaderText = ""
.Columns(0).AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill
End With
DataAdapter = Nothing
Dataset = Nothing
SQLConn.Close()
With buttonColumn
.Name = "DeleteButtonColumn"
.HeaderText = ""
.Text = "Delete"
.UseColumnTextForButtonValue = True
.AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill
.Width = 50
End With
If DataGridView1.Columns.Count = 1 Then
DataGridView1.Columns.Add(buttonColumn)
End If
End Sub
Screenshots:
Turns out that the columns where autoregenerating causing column re-arrangement on each the second click. Just set DataGridView1.AutoGenerateColumns = false in both the form load and event and it works.