vb.net Form wont start it just closes - vb.net

I set my first form to my login page but when i start it, It closes immediately
Private Sub login_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim ToolTip1 As New ToolTip()
ToolTip1.AutoPopDelay = 5000
ToolTip1.InitialDelay = 1000
ToolTip1.ReshowDelay = 500
ToolTip1.ShowAlways = True
ToolTip1.SetToolTip(Me.txt_pword, "Enter password here!")
ToolTip1.SetToolTip(Me.txt_username, "Enter username here!")
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles btn_login2.Click
dbconn = New SqlConnection
dbconn.ConnectionString = ("Data Source=JENELIE\SQLEXPRESS;Initial Catalog=LDESfeeding_DB;User ID=sa;Password=Jenelie19")
Dim reader As SqlDataReader
Try
dbconn.Open()
Dim sql As String
sql = "select * from auth_pword where Password = '" & txt_pword.Text & "' and username = '" & txt_username.Text & "' "
dbcomm = New SqlCommand(sql, dbconn)
reader = dbcomm.ExecuteReader
Dim ctr As Integer
ctr = 0
While reader.Read
ctr = ctr + 1
End While
If ctr = 1 Then
MessageBox.Show("Login Successful!")
homepage.Show()
Me.Close()
Else
MessageBox.Show("Incorrect Username or Password!")
End If
dbconn.Close()
Catch ex As SqlException
MessageBox.Show(ex.Message)
End Try
End Sub
End Class
That's the whole code in that form. I don't know what's causing it to close.
I tried to change the .Close() to .Hide() still nothing changes.

Related

Access denied during production

The code below works as intended in DEBUG with no errors. I input my search parameters, the record returns and populates all textboxes and loads the PDF file into the AxAcroPDF1 viewer.
However, after I compile and install the program I am receiving the error "Access to the path 'C:\Program Files (x86)\NAME OF PROGRAM\temp.file' is denied'
This only occurs when I search for a record and the PDF (in Binary format in the DB) to that record is supposed to load fails with the error message listed above. How can I resolve the permissions level (assuming this is the issue) to allow for the PDF to load? The area of concern presumably and more specifically is the LoadPDF() sub.
My code is as follows:
Imports System.Data.SqlClient
Public Class LoadDocs
Private DV As DataView
Private currentRow As String
Private Sub LoadDocs_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'TODO: This line of code loads data into the 'DocDataset.Documents_Table' table. You can move, or remove it, as needed.
Documents_TableTableAdapter.Fill(DocDataset.Documents_Table)
'Loads last record on to form
DocumentsTableBindingSource.Position = DocDataset.Documents_Table.Rows.Count - 1
DV = New DataView(DocDataset.Documents_Table)
'LoadPDF()
End Sub
Private Sub BtnOpenPDF_Click(sender As Object, e As EventArgs) Handles btnOpenPDF.Click
tbRecNumb.Clear()
tbFileName.Clear()
tbPetsLoadNumber.Clear()
tbBrokerLoadNumber.Clear()
tbFilePath.Clear()
Dim CurYear As String = CType(Now.Year(), String)
On Error Resume Next
OpenFileDialog1.Filter = "PDF Files(*.pdf)|*.pdf"
OpenFileDialog1.ShowDialog()
AxAcroPDF1.src = OpenFileDialog1.FileName
tbFilePath.Text = OpenFileDialog1.FileName
Dim filename As String = tbFilePath.Text.ToString
tbFileName.Text = filename.Substring(Math.Max(0, filename.Length - 18))
Dim loadnumber As String = tbFileName.Text
tbPetsLoadNumber.Text = loadnumber.Substring(7, 7)
End Sub
' Search for PETS Load Number, Broker Load Numberthen load record if found
Private Sub BtnSearchBtn_MouseEnter(sender As Object, e As EventArgs) Handles btnSearch.MouseEnter
Cursor = Cursors.Hand
btnSearch.BackgroundImage = My.Resources.ButtonDwn_Teal_Trans
End Sub
Private Sub BtnSearchBtn_MouseLeave(sender As Object, e As EventArgs) Handles btnSearch.MouseLeave
Cursor = Cursors.Default
btnSearch.BackgroundImage = My.Resources.Button_Teal_Trans
End Sub
Private Sub TbSearchInput_KeyDown(sender As Object, e As KeyEventArgs) Handles tbSearchInput.KeyDown
Cursor = Cursors.Hand
If e.KeyCode = Keys.Enter Then
Search()
End If
End Sub
Private Sub BtnSearch_Click(sender As Object, e As EventArgs) Handles btnSearch.Click
btnSearch.BackgroundImage = My.Resources.ButtonClk_Teal_Trans
Cursor = Cursors.Hand
Search()
End Sub
Private Sub Search()
Cursor = Cursors.WaitCursor
If cbColName.Text = "SEARCH BY:" Then
MeMsgBoxSearchCriteria.ShowDialog()
Else : lblSearchResults.Items.Clear()
Select Case DocDataset.Documents_Table.Columns(cbColName.Text).DataType
Case GetType(Integer)
DV.RowFilter = cbColName.Text & " = " & tbSearchInput.Text.Trim
Case GetType(Date)
DV.RowFilter = cbColName.Text & " = #" & tbSearchInput.Text.Trim & "#"
Case Else
DV.RowFilter = cbColName.Text & " LIKE '*" & tbSearchInput.Text.Trim & "*'"
End Select
If DV.Count > 0 Then
For IX As Integer = 0 To DV.Count - 1
lblSearchResults.Items.Add(DV.Item(IX)("PETS_LOAD_NUMBER"))
Next
If DV.Count = 1 Then
lblSearchResults.SelectedIndex = 0
Dim ix As Integer = DocumentsTableBindingSource.Find("PETS_LOAD_NUMBER", CInt(lblSearchResults.SelectedItem.ToString))
DocumentsTableBindingSource.Position = ix
LoadPDF()
Else
lblSearchResults.Visible = True
lblSearchResults.BringToFront()
End If
Else
' Display a message box notifying users the record cannot be found.
MeMsgBoxNoSearch.ShowDialog()
End If
End If
Cursor = Cursors.Default
End Sub
Private Sub LblSearchResults_SelectedIndexChanged(sender As Object, e As EventArgs) Handles lblSearchResults.SelectedIndexChanged
Dim ix As Integer = DocumentsTableBindingSource.Find("PETS_LOAD_NUMBER", CInt(lblSearchResults.SelectedItem.ToString))
DocumentsTableBindingSource.Position = ix
lblSearchResults.Visible = False
End Sub
Private Sub LoadPDF()
Dim temp = Environment.GetEnvironmentVariable("TEMP", EnvironmentVariableTarget.User)
If File.Exists(Application.StartupPath() & "\temp.file") = True Then
AxAcroPDF1.src = "blank.pdf"
My.Computer.FileSystem.DeleteFile(Application.StartupPath() & "\temp.file")
End If
Dim cmd As New SqlCommand
cmd.CommandText = "SELECT DOCUMENTS FROM Documents_Table WHERE PETS_LOAD_NUMBER = #pl"
cmd.Parameters.AddWithValue("#pl", tbPetsLoadNumber.Text)
cmd.CommandType = CommandType.Text
cmd.Connection = New SqlConnection With {
.ConnectionString = My.MySettings.Default.PETS_DatabaseConnectionString
}
Dim Buffer As Byte()
cmd.Connection.Open()
Buffer = cmd.ExecuteScalar
cmd.Connection.Close()
File.WriteAllBytes(Application.StartupPath() & "\temp.file", Buffer)
'DATA READER
AxAcroPDF1.src = Application.StartupPath() & "\temp.file"
End Sub
Private Sub DocumentsTableBindingSource_PositionChanged(sender As Object, e As EventArgs) Handles DocumentsTableBindingSource.PositionChanged
Try
currentRow = DocDataset.Documents_Table.Item(DocumentsTableBindingSource.Position).ToString
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub
Private Sub BtnSavePDF_Click(sender As Object, e As EventArgs) Handles btnSavePDF.Click
If tbPetsLoadNumber.Text.Length = 0 Then
MessageBox.Show("Please enter a PETS Load Number", "Missing Load Number", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
Exit Sub
ElseIf tbBrokerLoadNumber.Text.Length = 0 Then
MessageBox.Show("Please enter a Broker Load Number", "Missing Load Number", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
Exit Sub
ElseIf tbFileName.Text.Length = 0 Then
MessageBox.Show("Please enter a Filename", "Missing Filename", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
Exit Sub
End If
Try
Using OpenFileDialog As OpenFileDialog = OpenFileDialog1()
If (OpenFileDialog.ShowDialog(Me) = DialogResult.OK) Then
tbFilePath.Text = OpenFileDialog.FileName
Else 'Cancel
Exit Sub
End If
End Using
'Call Upload Images Or File
Dim sFileToUpload As String = ""
sFileToUpload = LTrim(RTrim(tbFilePath.Text))
'Initialize byte array with a null value initially.
Dim data As Byte() = Nothing
'Use FileInfo object to get file size.
Dim fInfo As New FileInfo(tbFilePath.Text)
Dim numBytes As Long = fInfo.Length
'Open FileStream to read file
Dim fStream As New FileStream(tbFilePath.Text, FileMode.Open, FileAccess.Read)
'Use BinaryReader to read file stream into byte array.
Dim br As New BinaryReader(fStream)
'Supply number of bytes to read from file.
'In this case we want to read entire file. So supplying total number of bytes.
data = br.ReadBytes(CInt(numBytes))
'Insert the details into the database
Dim cmd As New SqlCommand
cmd.CommandText = "INSERT INTO Documents_Table (BROKER_LOAD_NUMBER, PDF_FILENAME, PETS_LOAD_NUMBER, DOCUMENTS)
VALUES (#bl, #fn, #pl, #pdf)"
cmd.Parameters.Add("#fn", SqlDbType.NVarChar, 50).Value = tbFileName.Text
cmd.Parameters.Add("#pl", SqlDbType.Int).Value = tbPetsLoadNumber.Text
cmd.Parameters.Add("#bl", SqlDbType.NVarChar, 20).Value = tbBrokerLoadNumber.Text
cmd.Parameters.Add("#pdf", SqlDbType.VarBinary, -1).Value = data
cmd.CommandType = CommandType.Text
cmd.Connection = New SqlConnection With {
.ConnectionString = My.MySettings.Default.PETS_DatabaseConnectionString
}
cmd.Connection.Open()
cmd.ExecuteNonQuery()
cmd.Connection.Close()
MsgBox("File Successfully Imported to Database")
Catch ex As Exception
MessageBox.Show(ex.ToString())
End Try
End Sub
End Class
In your function LoadPDF you create a reference to tempdir and then don't use it. Instead, you use Application.StartupPath() which will point to C:\Programs(x86) and is usually not writeable without admin rights.
But why don't you use your temp dir:
Dim temp = SpecialDirectories.Temp 'more robust approach to get tempdir
If File.Exists(temp & "\temp.file") = True Then
AxAcroPDF1.src = "blank.pdf"
My.Computer.FileSystem.DeleteFile(temp & "\temp.file")
End If
...
File.WriteAllBytes(temp & "\temp.file", Buffer)
'DATA READER
AxAcroPDF1.src = temp & "\temp.file"

Login form in VB.Net using Access database not working

I'm pretty sure this code used to allow me to login using the SQL statement below, but now it doesn't and just clears the text boxes.
There is also an error message that I would like displayed when the username and password do not match that in the database. This is, like the other one, a label that the visibility would need changing. I had this code:
Try
UserType = GetUserType(txtUsername.Text.Trim, txtPass.Text.Trim)
Catch ex As Exception
lblErrorMatch.Visible = True
End Try
However, this just clears the text boxes when the details do not match.
Imports System.Data.OleDb
Public Class frmLogin
Private DBCmd As New OleDbCommand
Private ConStr As String = "Provider=Microsoft.ACE.OLEDB.12.0;" &
"Data Source=|DataDirectory|\NewHotel.mdb;"
Private Sub btnLogIn_Click(sender As Object, e As EventArgs) Handles btnLogIn.Click
Dim UserType As Object
'Distinguishing beetween different users
If UserType Is Nothing Then
lblErrorEmpty.Visible = True
ElseIf UserType.ToString = "MANAGER" Then
frmHomeManager.Show()
ElseIf UserType.ToString = "RECEPTIONIST" Then
frmHomeReceptionist.Show()
End If
'Username and password not matching error message
'Empty textboxes error message
If txtUsername.Text = "" OrElse txtPass.Text = "" Then lblErrorEmpty.Visible = True : Exit Sub
txtUsername.Clear()
txtPass.Clear()
chkShowPass.Checked = False
End Sub
Private Function GetUserType(Username As String, Pass As String) As Object
Dim UserType As Object
'Pull username and password from the database to check against the entered login details
Using DBCon As New OleDb.OleDbConnection(ConStr),
DBCmd As New OleDbCommand("SELECT UserType FROM tblEmployeeLogin WHERE [Username] = #Username AND [Pass] = #Pass", DBCon)
DBCmd.Parameters.Add("#Username", OleDbType.VarChar).Value = Username
DBCmd.Parameters.Add("#Pass", OleDbType.VarChar).Value = Pass
DBCon.Open()
UserType = DBCmd.ExecuteScalar.ToString
End Using
Return UserType
End Function
Private Sub chkShowPass_CheckedChanged(sender As Object, e As EventArgs) Handles chkShowPass.CheckedChanged
'Show password when checkbox is checked
If chkShowPass.Checked = True Then
txtPass.PasswordChar = Nothing
ElseIf chkShowPass.Checked = False Then
txtPass.PasswordChar = "*"
End If
End Sub
Private Sub txtUsername_TextChanged(sender As Object, e As EventArgs) Handles txtUsername.TextChanged, txtPass.TextChanged
'Make error message disappear after text is enetered into either of the text boxes
lblErrorEmpty.Visible = False
lblErrorMatch.Visible = False
End Sub
Private Sub lnkClear_LinkClicked(sender As Object, e As LinkLabelLinkClickedEventArgs) Handles lnkClear.LinkClicked
txtUsername.Clear()
txtPass.Clear()
chkShowPass.Checked = False
End Sub
Private Sub btnClose_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnClose.Click
'Close the form down which stops the application
Me.Close()
End Sub
End Class
Thank you for your time :)
I recently made a login like what you're trying to do. Hopefully you understand this code and it helps:
Dim CMD As OleDbCommand = New OleDbCommand("SELECT * FROM Staff WHERE Login = '" & ID & "'", Con)
Dim user As String
Try
Con.Open()
Dim sdr As OleDbDataReader = CMD.ExecuteReader()
If (sdr.Read() = True) Then
user = sdr("Login")
MessageBox.Show("Login Successful!")
ActiveUser.IsLoggedIn = True
Else
MessageBox.Show("Invalid username or password!")
End If
Catch ex As Exception
MsgBox(ex.Message)
Finally
Con.Close()
End Try

Identifier expected? visual basic

im almost done with this and then that... hopefully someone will be able to help me (Really hope so atleast, cus i need to be done with this:P) (need more text cus there is to much code):
|error is there|>
Private Sub FlatButton1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles FlatButton1_Click. <|error is there|
Dim Conn As New MySqlConnection("Not going to publish this")
If FlatTextBox1.Text = "" Then
MsgBox("No username specified")
FlatTextBox2.Text = ""
Else
If FlatTextBox2.Text = "" Then
MsgBox("No password specified")
FlatTextBox1.Text = ""
Else
Try
Me.Text = "Logging in..."
Conn.Open()
Dim sqlquery As String = "SELECT * FROM Testing WHERE Username = '" & FlatTextBox1.Text & "';"
Dim data As MySqlDataReader
Dim adapter As New MySqlDataAdapter
Dim command As New MySqlCommand
command.CommandText = sqlquery
command.Connection = Conn
adapter.SelectCommand = command
data = command.ExecuteReader
While data.Read()
If data.HasRows() = True Then
If data(2).ToString = FlatTextBox2.Text Then
Me.Text = "Logged in!"
My.Settings.Username = FlatTextBox1.Text
MsgBox("Welcome " + data(1).ToString)
Home.Show()
Me.Close()
If data(3).ToString = "1" Then
My.Settings.Admin = "Yes"
Else
My.Settings.Admin = "No"
End If
End If
Else
MsgBox("Failed Login")
End If
End While
Catch ex As Exception
End Try
End If
End If
End Sub
End Class
Replace these Lines
Private Sub FlatButton1_Click(ByVal sender As System.Object, ByVal e
As System.EventArgs) Handles FlatButton1_Click
With
Private Sub FlatButton1_Click(sender As Object, e As EventArgs) Handles FlatButton1_Click

VB.net - If 1 then "Yes" if 0 then "no"

I have Database Software I am trying to make. The problem is I can't seem to find how to make this work, i'm new to this whole thing and have figured a lot out on my own but I can't seem to do this simple task?
I have a listView that displays the data from the SQl everything works great EXCEPT I need the dropdaown box the say yes or no but import into the SQL database a 1 or 0 and also in my list view i need it to display a Yes or a No instead of a 1 or a 0 ? Thanks IN Advance
Code:
Imports System.Data.SqlClient
Imports System.Data
Public Class cmListAll
Dim cn As New SqlConnection
Dim cmd As SqlCommand
Dim dr As SqlDataReader
Private Sub frmReg_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
With Me.cboActive
.Items.Add("Yes")
.Items.Add("No")
.SelectedIndex = 0
End With
Call connectMeToSQLServer("Data Source=Database;Initial Catalog=db_XXX;Integrated Security=False;Uid=sa; Pwd=PASS;")
Call showList()
End Sub
Private Sub cboActive_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs)
e.Handled = True
End Sub
Private Sub cboACTIVE_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs)
Me.txtCredentials.Focus()
End Sub
Sub connectMeToSQLServer(ByVal cnString As String)
Try
With cn
If .State = ConnectionState.Open Then .Close()
.ConnectionString = cnString
.Open()
End With
Catch ex As Exception
MsgBox(ex.Message.ToString)
End Try
End Sub
Function INC() As Boolean
For Each t In Me.GroupBox2.Controls
If TypeOf t Is TextBox Or TypeOf t Is ComboBox Then
End If
If t.Text = "" Then
INC = True
End If
Next
End Function
Sub showList()
cmd = New SqlCommand
cmd.Connection = cn
cmd.CommandText = "Select * from [Case Managers]"
dr = cmd.ExecuteReader
Me.ListView1.Items.Clear()
While dr.Read
With Me.ListView1
.Items.Add(dr(0))
With .Items(.Items.Count - 1).SubItems
.Add(dr(1))
.Add(dr(2))
.Add(dr(3))
.Add(dr(4))
End With
End With
End While
dr.Close()
End Sub
Sub clearMe()
For Each t In Me.GroupBox2.Controls
If TypeOf t Is TextBox Then
If t.Text <> "" Then
t.text = ""
End If
Me.cmdNew.Enabled = True
Me.cmdSave.Text = "&Save"
Me.cmdSave.Enabled = False
Me.cmdDelete.Enabled = False
Me.cboActive.SelectedIndex = 0
End If
Next
End Sub
Private Sub cmdNew_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdNew.Click
For Each t In Me.GroupBox2.Controls
If TypeOf t Is TextBox Then
If t.Text <> "" Then
t.text = ""
End If
End If
Next
Me.cmdNew.Enabled = False
Me.cmdSave.Tag = "SAVE"
Me.cmdSave.Text = "&Save"
Me.cmdSave.Enabled = True
Me.GroupBox2.Enabled = True
Me.txtfirstname.Focus()
End Sub
Private Sub cmdSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdSave.Click
Select Case Me.cmdSave.Tag
Case "SAVE"
If INC() = True Then
MsgBox("Please Complete All Fields!", MsgBoxStyle.Exclamation, "")
Exit Sub
Else
cmd = New SqlCommand
cmd.CommandText = "Insert Into [Case Managers](Firstname,Lastname,Credentials,Active) Values('" & Me.txtfirstname.Text & "', '" & Me.txtlastname.Text & "', '" & Me.txtCredentials.Text & "', '" & Me.cboActive.Text & "' )"
cmd.Connection = cn
cmd.ExecuteNonQuery()
MsgBox("Successfully Save!", MsgBoxStyle.Information, "")
End If
Case Else
cmd = New SqlCommand
cmd.Connection = cn
cmd.CommandText = "Update [Case Managers] Set firstname='" & Me.txtfirstname.Text & "', lastname='" & Me.txtlastname.Text & "', credentials='" & Me.txtCredentials.Text & "', active='" & Me.cboActive.Text & "' Where CaseMangerID = " & Me.ListView1.SelectedItems(0).Text & ""
cmd.ExecuteNonQuery()
MsgBox("Successfully Updated!", MsgBoxStyle.Information, "")
End Select
clearMe()
showList()
End Sub
Private Sub ListView1_DoubleClick(ByVal sender As Object, ByVal e As System.EventArgs) Handles ListView1.DoubleClick
cmd = New SqlCommand
cmd.Connection = cn
cmd.CommandText = "Select * from [Case Managers] Where CaseMangerID = " & Me.ListView1.SelectedItems(0).Text & " "
dr = cmd.ExecuteReader
dr.Read()
Me.txtfirstname.Text = dr(1)
Me.txtlastname.Text = dr(2)
Me.txtCredentials.Text = dr(3)
Me.cboActive.Text = dr(4)
dr.Close()
Me.GroupBox2.Enabled = True
Me.cmdSave.Enabled = True
Me.cmdSave.Tag = "UPDATE"
Me.cmdSave.Text = "&Update"
Me.cmdDelete.Enabled = True
End Sub
Private Sub cmdDelete_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdDelete.Click
If MsgBox("Delete This Record?", MsgBoxStyle.Question + MsgBoxStyle.YesNo) = MsgBoxResult.Yes Then
cmd = New SqlCommand
cmd.Connection = cn
cmd.CommandText = "Delete from [Case Managers] Where CaseMangerID =" & Me.ListView1.SelectedItems(0).Text & " "
cmd.ExecuteNonQuery()
MsgBox("Successfully Deleted!", MsgBoxStyle.Information, "")
Me.cmdDelete.Enabled = False
Me.cmdSave.Enabled = False
Call clearMe()
Call showList()
Else
Exit Sub
End If
End Sub
I assume you're looking at this line:
Me.cboActive.Text = dr(4)
? That's the only thing that looked to me like it might be displaying a yes/no field. You could just put a simple If/Else block there, but as there are several other significant flaws in how this code is structured, I thought it would be useful to re-write that whole method for you:
Private Sub ListView1_DoubleClick(ByVal sender As Object, ByVal e As System.EventArgs) Handles ListView1.DoubleClick
'Would be better to specify column names here
Dim sql As String = "Select * from [Case Managers] Where CaseMangerID = #CaseManager"
'Best practices in most cases call for creating a new connection object for each query
Using cn As New SqlConnection("connection string here"), _
cmd As New SqlCommand(sql, cn)
'This is how to do string substitution in sql to protect against sql injection
cmd.Parameters.Add("#CaseManager", SqlDbType.Int).Value = CInt(Me.ListView1.SelectedItems(0).Text)
Using dr As SqlDataReader = cmd.ExecuteReader()
dr.Read()
Me.txtfirstname.Text = dr(1)
Me.txtlastname.Text = dr(2)
Me.txtCredentials.Text = dr(3)
Me.cboActive.Text = If(dr(4)=0,"No","Yes")
dr.Close()
End Using
End Using 'No need to close the connection. The Using block takes care of it
'The old code would have the left the connection open if an exception was thrown,'
' which could eventually lock you out of the database
Me.GroupBox2.Enabled = True
Me.cmdSave.Enabled = True
Me.cmdSave.Tag = "UPDATE"
Me.cmdSave.Text = "&Update"
Me.cmdDelete.Enabled = True
End Sub
You'll need to do something similar later on to invert this for updates/inserts.
You can use DisplayMember/ValueMember pair:
Dim dict As New Dictionary(Of Integer, String)
dict.Add(0, "No")
dict.Add(1, "Yes")
With Me.cboActive
.DisplayMember = "Value"
.ValueMember = "Key"
.DataSource = dict.ToList()
.SelectedIndex = 0
End With
Dictionary may not the best choice of class here, but works as a proof of concept.
Then just use cboActive.SelectedValue and pass that to the SQL query.

How to insert, edit, delete image in SQL using vb.net

I can't Search and Edit using this Code. Insert is working. But Insert coding method is not sure (fileContent.ToString). And Search part and Update part is not working.
Dim fileContent As Byte() = My.Computer.FileSystem.ReadAllBytes(OpenFileDialog1.FileName)
Sub NormalUpdate(ByVal _Query)
con.Open()
Dim cmdUpdate As New SqlCommand(_Query)
cmdUpdate.Connection = con
cmdUpdate.CommandType = CommandType.Text
cmdUpdate.ExecuteNonQuery()
con.Close()
End Sub
Sub NormalSave(ByVal _Query)
con.Open()
Dim cmdSave As New SqlCommand(_Query)
cmdSave.Connection = con
cmdSave.CommandType = CommandType.Text
cmdSave.ExecuteNonQuery()
con.Close()
End Sub
Private Sub btnSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSave.Click
NormalSave("Insert into Registration values('" + txtMemberNo.Text + "','" + fileContent.ToString + "')")
End Sub
Private Sub btnSearch_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSearch.Click
con.Open()
Using cmd As New SqlClient.SqlCommand("Select MemberPicture From Registration where MemberNo = '" + txtMemberNo.Text + "'", con)
Using dr As SqlClient.SqlDataReader = cmd.ExecuteReader()
Using dt As New DataTable
dt.Load(dr)
Dim row As DataRow = dt.Rows(0)
Using ms As New IO.MemoryStream(CType(row("MemberPicture"), Byte()))
Dim img As Image = Image.FromStream(ms)
ProfilePic.Image = img
con.Close()
End Using
End Using
End Using
End Using
End Sub
Private Sub btnUpdate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnUpdate.Click
NormalUpdate("Update Registration set MemberPicture = '" + fileContent.ToString + "' where MemberNo = '" + txtMemberNo.Text + "'")
End Sub
Please help me. Thanks.
Not sure if this is what you are looking for, but I use the following to get and set images from a database:
Public Function GetClientImage(ID As String) As Image
Dim ClientPicture As Image = Nothing
Dim DS As DataSet = Nothing
'Populate DS here
If (DS IsNot Nothing) AndAlso (DS.Tables.Count > 0) AndAlso (DS.Tables(0).Rows.Count > 0) Then
Dim DR As DataRow = DS.Tables(0).Rows(0)
Try
Dim Pic As Object = DR!Picture
If Pic IsNot DBNull.Value Then
Dim Buffer As Byte() = CType(DR!Picture, Byte())
If Buffer IsNot Nothing AndAlso (Buffer.Length > 0) Then
Using MS As New IO.MemoryStream(Buffer, 0, Buffer.Length)
MS.Write(Buffer, 0, Buffer.Length)
ClientPicture = Image.FromStream(MS, True)
End Using
End If
End If
Catch ex As Exception
MessageBox.Show("Error retrieving Image: " & ControlChars.NewLine & ControlChars.NewLine & ex.ToString, My.Application.Info.AssemblyName, MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1)
End Try
End If
Return ClientPicture
End Function
and:
Public Function UpdateClientImage(ID As String, Pic As Image) As Integer
Dim Result As Integer = 0
If Client IsNot Nothing Then
Dim SQL As String = "UPDATE Clients SET Picture = #photo WHERE ID = '" & ID & "' ;"
Using SQLConn As New SqlClient.SqlConnection(ConnectionString)
Try
SQLConn.Open()
Using SQLCmd As New SqlClient.SqlCommand(SQL, SQLConn)
Dim PhotoParameter As New SqlClient.SqlParameter("#photo", SqlDbType.Image)
Dim MS As New IO.MemoryStream()
If Pic IsNot Nothing Then
Pic.Save(MS, Imaging.ImageFormat.Bmp)
End If
PhotoParameter.SqlValue = MS.GetBuffer
SQLCmd.Parameters.Add(PhotoParameter)
Result = SQLCmd.ExecuteNonQuery()
End Using
Catch ex As Exception
Dim Msg As String = "Unable to save Client's Picture"
If ex IsNot Nothing Then
Msg &= ":" & ControlChars.NewLine & ControlChars.NewLine & ex.ToString
End If
MessageBox.Show(Msg, My.Application.Info.AssemblyName, MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1)
Finally
If Not SQLConn.State = ConnectionState.Closed Then
SQLConn.Close()
End If
End Try
End Using
End If
Return Result
End Function
Private Sub btnSave_Click(sender As Object, e As EventArgs) Handles
Dim OpennFileDialog As OpenFileDialog
query = "update tblEmployeeSetup set dbImage = #dbImage where empy_id = '" + txtEmpId.Text + "' "
insertImage(query, "Data Saved...", lblSave, OpennFileDialog )
End Sub
Sub insertImage(ByVal query As String, ByVal message As String, ByVal lblSave As Label, ByVal a As OpenFileDialog)
Try
If con.State = ConnectionState.Closed Then
con.Open()
End If
' Dim result As DialogResult = a.ShowDialog()
' a.FileName = My.Resources.DefultImage.ToString
cmd.Connection = con
cmd.CommandText = query
cmd.Parameters.Add(New SqlClient.SqlParameter("#dbimage", SqlDbType.Image)).Value = IO.File.ReadAllBytes(a.FileName)
cmd.ExecuteNonQuery()
cmd.Parameters.Clear()
lblSave.Text = message
a.Dispose()
Catch ex As Exception
MessageBox.Show("Error" & ex.Message)
Finally
con.Close()
End Try
End Sub