Parameter is not valid - System.Drawing.Image.FromStream(Ms) - sql-server

I am trying to retrieve the image from the database for a particular user after logging into the program. The problem I encountered is "Parameter is not valid."
The code:
Dim ArrImage() As Byte
Dim cn As New SqlConnection("server=.\sqlexpress;Initial Catalog=hazimdb;Integrated Security=True")
Dim Ms As New IO.MemoryStream
Dim da As New SqlDataAdapter("SELECT * FROM userlog WHERE username= '" & Label10.Text.Trim & "'", cn)
Dim dt As New DataTable
da.Fill(dt)
If dt.Rows.Count <> 0 Then
Label10.Text = dt.Rows(0).Item("username")
If Not IsDBNull(dt.Rows(0).Item("pictu")) Then
ArrImage = dt.Rows(0).Item("pictu")
For Each arr As Byte In ArrImage
Ms.WriteByte(arr)
Next
PictureBox8.Image = System.Drawing.Image.FromStream(Ms)
End If
Else
MsgBox("No Match Found")
End If

Set the memory stream position to 0 before trying to get an image out of it.
Ms.Flush()
Ms.Position = 0

Related

Auto generate alpha numeric in VB.NET

I'm currently working on my project for which I used VB.NET 2019 and SQL server. I need to create a function which auto generates IDs.
I want my IDs to be like these: P001, P002, P003 etc. Can someone show me how to code it? Below is my code
Private Sub Form4_Load_1(sender As Object, e As EventArgs) Handles MyBase.Load
BindData()
Dim data As String = "Data Source=LAPTOP-M8KKSG0I;Initial Catalog=Oceania;Integrated Security=True"
Dim con As New SqlConnection(data)
Try
If Con.State = ConnectionState.Closed Then
con.Open()
End If
Dim sql As String = "Select Max(PatientID) from Patient"
Dim cmd As New SqlCommand(sql, con)
Dim Max As String = cmd.ExecuteScalar
If Max > 0 Then
TextBox1.Text = Max + 1
Else
TextBox1.Text = "P01"
End If
Catch ex As Exception
MsgBox(Err.Description)
End Try
End Sub
You can try like this. Here 1 is an auto-generated number that may be an identity key column value from a table in SQL Server.
Dim number As Integer = 1
Dim numberText As String = "P" & number.ToString().PadLeft(3, "0")
Live demo
You can add a computed column like this in your table for auto-generating the sequences. This will reduce the chances of duplicate value runtime once more than one person will do the entry simultaneously.
Alter table Patient ADD PatientCode AS ('P' + Convert(Varchar(3),CONCAT(REPLICATE('0', 3 - LEN(PatientID)), PatientID)) )
To get the column value dynamically you can try the below code to generate function.
Private Sub GenerateSequnce()
Dim constring As String = "Data Source=TestServer;Initial Catalog=TestDB;User id = TestUser;password=test#123"
Using con As New SqlConnection(constring)
Using cmd As New SqlCommand("Select Top 1 ISNULL(TaxCode, 0) from Tax_Mst Order By TaxCode Desc", con)
cmd.CommandType = CommandType.Text
Using sda As New SqlDataAdapter(cmd)
Using dt As New DataTable()
sda.Fill(dt)
Dim maxNumberCode = dt.Rows(0)("TaxCode").ToString()
If (maxNumberCode = "0") Then
maxNumberCode = "1"
End If
Dim numberText As String = "P" & maxNumberCode.ToString().PadLeft(3, "0")
End Using
End Using
End Using
End Using
End Sub
Here the column TaxCode is int with identity constraint.
With the minor correction in your code, you can achieve this as shown below.
Dim data As String = "Data Source=LAPTOP-M8KKSG0I;Initial Catalog=Oceania;Integrated Security=True"
Dim con As New SqlConnection(data)
Try
If con.State = ConnectionState.Closed Then
con.Open()
End If
Dim sql As String = "Select ISNULL(Max(PatientID), 0) from Patient"
Dim cmd As New SqlCommand(sql, con)
Dim Max As String = cmd.ExecuteScalar
If (Max = "0") Then
Max = "1"
Else
Max = CInt(Max) + 1
End If
Dim numberText As String = "P" & Max.ToString().PadLeft(3, "0")
TextBox1.Text = numberText
Catch ex As Exception
MsgBox(Err.Description)
End Try
OUTPUT

Avoid Duplicate record across columns

I Have a code that will determine if a data is already existing. The problem is, it is still adding even already exists.
Already tried some code that will add and not add if data exists
If txtHostname.Text = "" Then
MsgBox("Please fill-up all fields!", MsgBoxStyle.Exclamation, "Inventory!")
Else
Dim theQuery As String = "SELECT * FROM Asset WHERE Monitor1=#Monitor1 AND Monitor2=#Monitor2"
Dim cmd1 As OleDbCommand = New OleDbCommand(theQuery, con)
cmd1.Parameters.AddWithValue("#Monitor1", txtMonitor1.Text)
cmd1.Parameters.AddWithValue("#Monitor2", txtMonitor2.Text)
Using reader As OleDbDataReader = cmd1.ExecuteReader()
If reader.HasRows Then
' User already exists
MsgBox("User Already Exist!", MsgBoxStyle.Exclamation, "Add New User!")
Else
' User does not exist, add them
Dim cmd As OleDbCommand = New OleDbCommand("Insert into Asset ([Monitor1],[Monitor2]) values ('" + txtMonitor1.Text + "','" + txtMonitor2.Text + "')", con2)
cmd.ExecuteNonQuery()
MsgBox("Records Successfully Added!", MsgBoxStyle.Information, "Add New Customer!")
txtMonitor1.Text = ""
txtMonitor2.Text = ""
End If
End Using
con.Close()
End If
It should be, when I search 1 data in column1 it should detect if data is already exists in column1 and column2. Not just in column1.
Well, if you want to search and return the result about whether Fields exist or not , you should not use OledbReader, also I did notice that reader doesn't Read (Even if it is not even correct to use it in this scenario). You could rather use ExecuteScalar and see if Fields exist or not (>0 or <0).
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim CMDText As String = ("SELECT COUNT(*) FROM Asset WHERE Monitor1=#Monitor1 AND Monitor2=#Monitor2")
Dim Found As Integer
If String.IsNullOrEmpty(txtHostname.Text) Then
MsgBox("Please fill-up all fields!", MsgBoxStyle.Exclamation, "Inventory!")
Else
Using CN As New OleDb.OleDbConnection With {.ConnectionString = "CON_STR"},
Cmd1 As New OleDb.OleDbCommand(CMDText, CN)
CN.Open()
With Cmd1.Parameters
.Add("#Monitor1", OleDb.OleDbType.VarChar).Value = txtMonitor1.Text
.Add("#Monitor2", OleDb.OleDbType.VarChar).Value = txtMonitor2.Text
End With
Found = Cmd1.ExecuteScalar()
End Using
If Found > 0 Then
' User already exists
MsgBox("User Already Exist!", MsgBoxStyle.Exclamation, "Add New User!")
Else
Dim CmdText1 As String =
("INSERT INTO Asset (Monitor1,Monitor2) VALUES (#Monitor1 ,#Monitor2)")
Using Cmd As New OleDb.OleDbCommand(CmdText1, CN)
With Cmd.Parameters
.Add("#Monitor1", OleDb.OleDbType.VarChar).Value = txtMonitor1.Text
.Add("#Monitor2", OleDb.OleDbType.VarChar).Value = txtMonitor2.Text
End With
Cmd.ExecuteNonQuery()
' User does not exist, add them
MsgBox("Records Successfully Added!", MsgBoxStyle.Information, "Add New Customer!")
txtMonitor1.Text = String.Empty
txtMonitor2.Text = String.Empty
Cmd.Parameters.Clear()
End Using
End If
End If
End Sub
In my example Code : "CON_STR" = My ConnectionString that I used to test my Code, as you did not provide any.

Database only adds (x) amount of rows before error system resources exceeded

I am having a problem with my code where i am only able to add so many lines of text before i get an error "system resources exceeded".
This is my code:
Dim x As Integer = MsgBox("Update Record?", MsgBoxStyle.YesNo, "Are you sure?")
If x = MsgBoxResult.Yes Then
Dim accessconn As New _
System.Data.OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & "MyDB.accdb")
Dim com As System.Data.OleDb.OleDbCommand
accessconn.Close()
Try
For Each strLine As String In TextBox1.Text.Split(vbNewLine)
accessconn.Open()
Dim str As String
Dim dr As OleDbDataReader
str = "SELECT * FROM Table4 WHERE MD5='" & strLine & "'"
Dim cmd As OleDbCommand = New OleDbCommand(str, accessconn)
dr = cmd.ExecuteReader
If dr.Read() Then
Label2.Text = Label2.Text + 1
Else
accessconn.Open()
com = New System.Data.OleDb.OleDbCommand("INSERT INTO Table4(MD5) VALUES('" & strLine & "')", accessconn)
com.ExecuteReader(CommandBehavior.CloseConnection)
Label3.Text = Label3.Text + 1
com.Dispose()
accessconn.Close()
End If
Next
accessconn.Close()
Catch ex As Exception
MsgBox(ex.ToString)
End Try
MsgBox("Done")
PopulateGridview4()
End If
I would like to be able to add unlimited rows of text to the database if possible. Please Help.
You should change your code to something like the following. Note that
Everything that returns an object like OleDbConnection, OleDbCommand, or OleDbDataReader is wrapped in a Using block. These objects all implement the IDisposable interface, which means they should be cleaned up as soon as you're done with them.
Also note that your INSERT did not return any data, so you should use ExecuteNonQuery instead of ExecuteReader.
Finally, please don't get into the habit of putting Try/Catch/End Try blocks around everything. You were displaying the exception (you displayed ex.ToString, which is a good thing), but you then ignored the exception. As a good general rule, don't catch exceptions unless you can fix them.
Code:
Dim x As Integer = MsgBox("Update Record?", MsgBoxStyle.YesNo, "Are you sure?")
If x = MsgBoxResult.Yes Then
Using accessconn As New _
System.Data.OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & "MyDB.accdb")
accessconn.Open()
For Each strLine As String In TextBox1.Text.Split(vbNewLine)
Dim str As String = "SELECT * FROM Table4 WHERE MD5='" & strLine & "'"
Using cmd As OleDbCommand = New OleDbCommand(str, accessconn)
Using dr As OleDbDataReader = cmd.ExecuteReader
If dr.Read() Then
Label2.Text = Label2.Text + 1
Else
Using com As OleDbCommand = New System.Data.OleDb.OleDbCommand("INSERT INTO Table4(MD5) VALUES('" & strLine & "')", accessconn)
com.ExecuteNonQuery()
End Using
Label3.Text = Label3.Text + 1
End If
End Using
End Using
Next
MsgBox("Done")
PopulateGridview4()
End Using
End If
P.S. you could probably have made this a little less indented by using If x <> MsgBoxResult.Yes Then get out, but I don't know if this is inside of a Sub or Function, so "get out" could be different.

Update command only updates first row vb.net

I'm trying to update a database through a datagridview but the problem I'm having is that it only updates the first row in the datagridview. Any insight will be grateful, thanks.
Dim Connection As New OleDbConnection(Get_Constring)
Dim dt As DataTable = New DataTable("SendTable")
Dim row As DataRow
dt.Columns.Add("ID", Type.GetType("System.Int32"))
dt.Columns.Add("Attendance", Type.GetType("System.String"))
For i = 0 To ClassRegisterdgv.Rows.Count - 1
' If ClassRegisterdgv.Rows(i).Cells(4).Value.Equals("") Then ClassRegisterdgv.Rows(i).Cells(4).Value.Equals("Present")
Dim ID As Integer = ClassRegisterdgv.Rows(i).Cells(0).Value
Dim Attendance As String = ClassRegisterdgv.Rows(i).Cells(4).Value
row = dt.Rows.Add
row.Item("ID") = ID
row.Item("Attendance") = Attendance
Next
If Connection.State = ConnectionState.Closed Then
Connection.Open()
End If
Dim sqlquery As String = "UPDATE PupilInfo SET " & NewColumnCreated & " = #Attendance WHERE ID = #ID"
Dim sqlcommand As New OleDbCommand
For Each newrow As DataRow In dt.Rows
'For i = 0 To ClassRegisterdgv.Rows.Count - 1
With sqlcommand
.CommandText = sqlquery
.Parameters.AddWithValue("#Attendance", newrow.Item(1))
.Parameters.AddWithValue("#ID", newrow.Item(0))
.Connection = Connection
MessageBox.Show(newrow.Item(1) & newrow.Item(0))
.ExecuteNonQuery()
End With
Next
Connection.Close()
ClassRegisterdgv.DataSource = Nothing
dt.Clear()
Only updates the first row because the parameters collection of the command object has not been cleaned. Try to do the following:
With sqlcommand
.CommandText = sqlquery
.Parameters.Clear() '<─────── Insert this line in your code.
.Parameters.AddWithValue("#Attendance", newrow.Item(1))
.Parameters.AddWithValue("#ID", newrow.Item(0))
.Connection = Connection
MessageBox.Show(newrow.Item(1) & newrow.Item(0))
.ExecuteNonQuery()
End With

Graph Not Drawing Values vb.net

dtTest.Columns.Add("TestName", GetType(String))
dtTest.Columns.Add("Score", GetType(Integer))
Dim cn As New OleDbConnection(connectionString)
cn.Open()
Dim cmd As New OleDbCommand("SELECT * From ScoreDB WHERE StudentName='" & SelectStudent.Text & "'", cn)
cmd.ExecuteNonQuery()
Dim reader As OleDbDataReader = cmd.ExecuteReader()
While (reader.Read())
Dim TestName As String = Convert.ToString(reader("TestName"))
Dim TestScore As String = Convert.ToString(reader("ScorePercentage"))
GraphValues.Add(TestName, TestScore)
End While
Dim point As KeyValuePair(Of String, Integer)
For Each point In GraphValues
dtTest.Rows.Add(point.Key)
dtTest.Rows.Add(point.Value)
MsgBox(point.Key)
Next
With Chart1.ChartAreas(0)
.AxisX.Minimum = 0
.AxisX.Maximum = 10
.AxisY.Minimum = 0
.AxisY.Maximum = 100
.AxisY.Interval = 10
.AxisX.Title = "Test"
.AxisY.Title = "Score Percentage"
End With
cn.Close()
End Sub
I've created a form that should output a the score and test name into a column chart in vb.net, It loads all the data from the database successfully but it fails to write it to the graph and ends up just like this
any help would be appreciated as I am really struggling with this at the moment and have searched various resources such as MSDN.
Nothing is telling the chart to map the datatable GraphValues to the chart. Try something like below. You may to tinker around with the code slightly
Chart1.DataSource = GraphValues
Chart1.Series(0).XValueMember = "TestName"
Chart1.Series(0).YValueMembers = "Score"
'Data bind to the selected data source
Chart1.DataBind()
http://blogs.msdn.com/b/alexgor/archive/2009/02/21/data-binding-ms-chart-control.aspx

Resources