Data binding WPF populating combobox from mysql database Vb.net - wpf

Hi am converting my old winform app to WPF. Just getting started with it.
How do bind data from mysql table to a combobox. Below is my winform code which works.
Try
mysqlcnx.Open()
Dim da As New MySqlDataAdapter("select * from mydb.eventlist", mysqlcnx)
Dim table As New DataTable()
da.Fill(table)
ComboBox1.DataSource = New BindingSource(table, Nothing)
ComboBox1.DisplayMember = "EventName"
ComboBox1.SelectedIndex = -1
Catch ex As Exception
MsgBox(ex.Message)
End Try
I tried converting it like this but doesnt work.
Try
conn.Open()
Dim da As New MySqlDataAdapter("select * from mydb.eventlist", conn)
Dim table As New System.Data.DataTable()
da.Fill(table)
'EventcomboCon.ItemsSource = New BindingGroup(table, Nothing)
EventcomboCon.DisplayMemberPath = "EventName"
EventcomboCon.SelectedIndex = -1
Catch ex As Exception
MsgBox(ex.Message)
End Try

By searching the web, I was able to determine that the code should be like this:
With myComboBox
.DisplayMemberPath = "EventName"
.ItemsSource = myDataTable.AsEnumerable()
End With
You should have been able to find that same information.

Related

The connection was not closed the connection current state is open

Hye... I currently doing my final year project using vb.net and i got this error. Im tryin' to fix the error but still not succeed. I use ms access for database in my project. I try to put con.Open() before the 'dt' statement and con.Close() after the 'cboProduct.Select' but the result is the same. Really appreciate your helps. Thanks :)
'GLOBAL DECLARATIONS
Dim conString As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Acer User\Documents\MAKLUMAT IVENTORI.accdb"
Dim con As OleDbConnection = New OleDbConnection(conString)
Dim adapter As New OleDbDataAdapter
Dim cmd As New OleDbCommand
Dim dt As New DataTable
Dim ds As New DataSet
Private Sub RefreshData()
dt = New DataTable
ds = New DataSet
ds.Tables.Add(dt)
adapter = New OleDbDataAdapter("Select * FROM product WHERE lab_kod='66'", con)
adapter.Fill(dt)
DataGridView1.DataSource = dt.DefaultView
labelID.Text = getAutoID()
lblLabCode.Text = "66"
cboProduct.Select()
Dim v_SQL As String = "SELECT * FROM kategori_product"
cmd = New OleDbCommand(v_SQL, con)
con.Open()
Dim v_dataReader As OleDbDataReader = cmd.ExecuteReader()
Dim v_dataTable As New DataTable
v_dataTable.Columns.Add("product_kod", Type.GetType("System.String"))
If v_dataReader.HasRows Then
While v_dataReader.Read
v_dataTable.Rows.Add(v_dataReader.GetString(0))
End While
cboProduct.DataSource = v_dataTable
End If
cboProduct.DisplayMember = "product_kod"
cboProduct.ValueMember = "product_kod"
v_dataReader.Close()
con.Close()
End Sub
Don't store short-lived objects, such as database connections, as global variables.
In fact, don't use global variables, ever, at all.
(though I note that assuming this is a Class and not a Module those are actually class fields, not globals, but you're still misusing them)
Your OleDbDataAdapter.Fill call requires the connection to be open, but you call .Fill(dt) before calling con.Open()
Use Using (using() in C#) blocks to ensure your database connection is always closed, even in the event of failure.

VB.Net Open image from database to picturebox

I'm trying to open an image from my database to a picture box but I just don't how to do it.
I've searched for some answers and I am not familiar with the codes for I am beginner only.
The only codes that I researched about are for connecting the database to the system:
Imports System.Data.OleDb
Module Module1
Public acsconn As New OleDbConnection
Public acsdr As OleDbDataReader
Public acsda As New OleDbDataAdapter
Public acscmd As New OleDbCommand
Public strsql As String
Public acsds As New DataSet
Public Sub connect()
Try
acsconn.ConnectionString = "provider=microsoft.jet.oledb.4.0; data source=|datadirectory|\database1.mdb;"
acsconn.Open()
If acsconn.State = ConnectionState.Open Then
MsgBox("Connected")
Else
MsgBox("Error")
End If
Catch ex As Exception
End Try
End Sub
End Module
I do not know what is next. BTW, those codes - I used it for saving the image to the database.
I think this is the sort of thing you are looking for:
Private Sub HandleRequest(context as HttpContext)
Dim SqlCnn As SqlConnection = Nothing, sql As String
Dim emp_id As Integer
emp_id = Int32.Parse(context.Request.QueryString("id"))
ConnectDB(SqlCnn)
Try
sql = "SELECT image FROM employees (NOLOCK) WHERE ID =" & emp_id
sqlcmd = New SqlCommand(sqlstr, SqlCnn)
Dim imageData As Byte() = DirectCast(sqlcmd.ExecuteScalar(), Byte())
context.Response.ContentType = "image/jpeg"
context.Response.BinaryWrite(imageData)
Catch ex As Exception
ReportError(ex)
Finally
CloseDB(SqlCnn)
End Try
End Sub

Loading data from SQL Server row by row to textboxes

I am trying to retrieve data row by row from my SQL Server and load them into my respective textboxes, I was doing the below code but of course it doesn't work as the For Each loop will load every single textboxes with each data retrieved, ran out of ideas. Appreciate if someone can give me a boost here. Thanks.
Private Sub retrieve_Data()
Dim con As New SqlConnection
Dim cmd As New SqlCommand
Try
con.ConnectionString = "Data Source=HPEnvy-HP; Initial Catalog=Cinema; User Id=<id>; Password=<password>;"
con.Open()
cmd.Connection = con
cmd.CommandText = "SELECT [movie_ID], [movie_Title] FROM [Movie_Table] ORDER BY [MOVIE_ID] "
Dim lrd As SqlDataReader = cmd.ExecuteReader()
While lrd.Read()
Dim reader As String = lrd(1).ToString
Dim arrLoad As New ArrayList
arrLoad.Add(lrd(1).ToString)
For i = 0 To arrLoad.Count - 1
For Each cCtrl As Control In Panel1.Controls
If TypeOf cCtrl Is TextBox Then
Dim txtBox As New TextBox
txtBox = cCtrl
txtBox.Text = arrLoad.Item(i)
End If
Next
Next
End While
Catch ex As Exception
MessageBox.Show("Error while retrieving records on table..." & ex.Message, "Load Records")
Finally
con.Close()
End Try
End Sub
you just "new" your textbox,
you didn't add your textbox to your form.
you should add some code like that:
this.Controls.Add(textbox);
or
this.Panel1.Controls.Add(textbox);

how to save binary file to database

Join Date: Dec 10
Posts: 10
caba11 is an unknown quantity at this point (<10)
how to save binary file to database
hi.
i need to save files into database...
i cant find why it is not working...
this is my code:
Public Sub importfiles(ByVal sFileName As String)
Dim cnSQL As SqlConnection
Dim cmSQL As SqlCommand
Dim strSQL
'Validate form values
'Read file into a stream
Dim fs As New FileStream(sFileName, FileMode.Open, FileAccess.Read)
Dim myData(fs.Length) As Byte
fs.Read(myData, 0, fs.Length)
fs.Close()
Try
'Build SQL
strSQL = "insert into data_cesta(ID, cesta) values (#ID, #cesta)"
cnSQL = New SqlConnection("Data Source=.;AttachDbFilename=|DataDirectory|\Database1.mdf;Integrated Security=True;User Instance=True")
cmSQL = New SqlCommand(strSQL, cnSQL)
cmSQL.Parameters.Add(New SqlParameter("#ID", SqlDbType.Int)).Value = ID
cmSQL.Parameters.Add(New SqlParameter("#cesta", SqlDbType.NText)).Value = myData
' cmd2.Parameters.Add("#ID", SqlDbType.Int).Value = ID
' cmd2.Parameters.Add("#cesta", SqlDbType.NText).Value = myData
'Open connection and execute the command
cnSQL.Open()
cmSQL.ExecuteNonQuery()
'Close and clean up objects
cnSQL.Close()
cmSQL.Dispose()
cnSQL.Dispose()
Catch ex As SqlException
MsgBox(ex.Message, MsgBoxStyle.Critical, "SQL Error")
Catch ex As Exception
MsgBox(ex.Message, MsgBoxStyle.Critical, "General Error")
End Try
End Sub
without try it says "cmSQL.ExecuteNonQuery()"-"Failed to convert parameter value from a DataGridViewTextBoxColumn to a Int32."
It looks as though you are loading some file paths into a DataGrid before having them processed into your database.
By default, your ID field is being passed to the procedure as the DataGridViewTextBoxColumn object within the DataGrid. You need to retrieve the text within that object.
You can do so by accessing the associated DataGridViewTextBoxCell object on the row being processed. Within the DataGridViewTextBoxCell object is a property called "Value" which will have the ID value you need.
Without seeing more code, it's hard to give you the exact code, but check out the DataGridViewCell object for some helpful code, since the TextBoxCell inherits from this class.

display/retrieve image from sql database in vb.net

This should be pretty simple for a pro. I have images in sql server database and I want to retrieve them in my aspx (vb.net) file.
I have in aspx this image control -
in vb.net i have started this code -
Private Sub ImageDisplay()
Dim SqlCnn As SqlConnection = Nothing, sql As String = ""
ConnectDB(SqlCnn)
Try
sql = "SELECT image FROM employees (NOLOCK) WHERE ID =" & emp_id
sqlcmd = New SqlCommand(sqlstr, SqlCnn)
Dim imageData As Byte() = DirectCast(sqlcmd.ExecuteScalar(), Byte())
Dim newImage As Image = Nothing
If Not imageData Is Nothing Then
Using ms As New MemoryStream(imageData, 0, imageData.Length)
ms.Write(imageData, 0, imageData.Length)
newImage = Image.FromStream(ms, True)
End Using
image1.Image = newImage
End If
Catch ex As Exception
ReportError(ex)
Finally
CloseDB(SqlCnn)
End Try
End Sub
I am getting error on 2 places.
- newImage = Image.FromStream(ms, True)
- image1.Image = newImage
Fromstream is not a member of system.web.ui.webcontrols.image
and second error Image is not a member of system.web.ui.webcontrols.image
You need both a command object and a data reader. However, you are putting them in the wrong page.
If you check out the properties of the Image control you will see that it doesn't have any Image property, so you can't load an image and put in the control. The reason for that is that you can't send both the page and the image in the same response, instead the browser has to request the image separately when the page loads.
To get the image from the database and show in the web page you need a separate proxy page that you can use to get only the image data from the database. In the ImageUrl property of the Image control you would put something like "GetImage.ashx". Then you make an HTTP handler with that name that will just get the image data from the database and write to the response stream.
Example:
Private Sub HandleRequest(context as HttpContext)
Dim SqlCnn As SqlConnection = Nothing, sql As String
Dim emp_id As Integer
emp_id = Int32.Parse(context.Request.QueryString("id"))
ConnectDB(SqlCnn)
Try
sql = "SELECT image FROM employees (NOLOCK) WHERE ID =" & emp_id
sqlcmd = New SqlCommand(sqlstr, SqlCnn)
Dim imageData As Byte() = DirectCast(sqlcmd.ExecuteScalar(), Byte())
context.Response.ContentType = "image/jpeg"
context.Response.BinaryWrite(imageData)
Catch ex As Exception
ReportError(ex)
Finally
CloseDB(SqlCnn)
End Try
End Sub
Dim cn As SqlConnection
cn = New SqlConnection
cn.ConnectionString = "Data Source=UMAR\UMAR;Initial Catalog=DMCHS;Integrated Security=True"
Dim cmd As New System.Data.SqlClient.SqlCommand("select D1 from DBFile where mem_no=2")
cmd.Connection = cn
cmd.CommandType = CommandType.Text
Dim ImgStream As New IO.MemoryStream(CType(cmd.ExecuteScalar, Byte()))
PictureBox1.Image = Image.FromStream(ImgStream)
ImgStream.Dispose()
cmd.Connection.Close()

Resources