i need to upload and display images to and from database. i have written this code for uploading and it uploads fine. except 1 problem. It crashes when i dont select an image. can someone help me fix it for null value? also how do you display an image in IE?
code for inserting image -
Dim imageInfo As FileInfo = Nothing
Dim data() As Byte = Nothing
imageInfo = New FileInfo(Me.UploadLogo.Value.Trim())
Dim imagestream As FileStream = New FileStream(imageInfo.ToString, FileMode.Open)
if name_id > 0
ReDim data(imagestream.Length - 1)
imagestream.Read(data, 0, imagestream.Length)
imagestream.Close()
Sqlstr = "UPDATE logos WITH(ROWLOCK) " & _
"SET Logo=#Logo,Modified_Date=GETDATE() " & _
"WHERE ID = " + name_id.ToString + ""
Else
Sqlstr = "INSERT logos (Logo,Created_Date) " & _
"VALUES ("#Logo,GETDATE())"
End If
SqlCmd = New SqlCommand(Sqlstr, SqlCnn)
Dim pictureParameter As SqlParameter = Nothing
pictureParameter = New SqlParameter("#Logo", SqlDbType.Image)
pictureParameter.Value = data
SqlCmd.Parameters.Add(pictureParameter)
SqlCmd.ExecuteScalar()
this works fine only if an image is selected, crashes for NULL values.
Also please help me with image display. thanks
To solve your "file not selected problem", you should have an If statement along the lines of:
If Not File.Exists(Me.UploadLogo.Value.Trim())
' Exit out or handle no file selected
End If
Related
I am working on an existing database structure. The database has a field to store PDF/Word/Jpeg files as images. Unfortunately I cannot change the database field format.
I am able to successfully read the pdf stored as image and display the pdf file, but cannot get to insert the image in database. I tried different version from many sites, but could not get it to work.
Here is my current code
Dim sql As String
Dim da As New OleDb.OleDbDataAdapter
Dim sqlquery As New OleDb.OleDbCommand
Dim sqlconn As New OleDb.OleDbConnection
Try
sqlconn.ConnectionString = dbConnectStr1
sqlquery.Connection = sqlconn
sqlconn.Open()
For cnt1 = 0 To dgv1.Rows.Count - 1
Dim fInfo As New FileInfo(dgv1.Rows(cnt1).Cells(3).Value)
Dim numBytes As Long = fInfo.Length
Dim fStream As New FileStream(dgv1.Rows(cnt1).Cells(3).Value, FileMode.Open, FileAccess.Read)
Dim br As New BinaryReader(fStream)
Dim data As Byte() = br.ReadBytes(CInt(numBytes))
br.Close()
fStream.Close()
sql = "INSERT INTO " & attachmentTbl & " (DocID, DocName, DocType, DocFile, DocLength) " &
"VALUES ('" & dgv1.Rows(cnt1).Cells(0).Value & "', '" & dgv1.Rows(cnt1).Cells(1).Value & "', '" & dgv1.Rows(cnt1).Cells(2).Value & "', " data ", " & numBytes & ")"
sqlquery.CommandText = sql
'"VALUES (#DocID, #DocName, #DocType, #DocFile, #DocLength)"
'sqlquery.OleDbParameter.Add(New System.Data.SqlClient.SqlParameter("#DocID", dgv1.Rows(cnt1).Cells(0).Value))
'sqlquery.Parameters.Add(New System.Data.SqlClient.SqlParameter("#DocName", dgv1.Rows(cnt1).Cells(1).Value))
'sqlquery.Parameters.Add(New System.Data.SqlClient.SqlParameter("#DocType", dgv1.Rows(cnt1).Cells(2).Value))
'sqlquery.Parameters.Add(New System.Data.SqlClient.SqlParameter("#DocFile", data))
'sqlquery.Parameters.Add(New System.Data.SqlClient.SqlParameter("#DoDocLength", numBytes))
'sqlquery.ExecuteNonQuery()
Next
sqlconn.Close()
Catch ex As Exception
errorFlag = True
MessageBox.Show("Error#060 " & ex.Message)
Exit Sub
End Try
Also, Is there a way to get the file type displayed in windows explorer. I.e. for .pdf file the display with would "adobe acrobat document" .xls file would be "Microsoft excel worksheet"
I tried using the below code but I don't get the above stuff
extn = Path.GetExtension(txtFileName.Text)
Dim regKey As Microsoft.Win32.RegistryKey = Microsoft.Win32.Registry.ClassesRoot.OpenSubKey(extn)
If Not regKey Is Nothing Then
Dim ct As Object = regKey.GetValue("Content Type")
If Not ct Is Nothing Then
extn = ct.ToString()
End If
End If
Appreicate your help.
So I have instant messaging functionality that I use with a database. Each time a message is sent it prints what's in the message column in the database into a rich text box in my vb.net application
My problem is. I have to click on the "send message" button twice to get the functionality to work, as the first time I click it, nothing happens
Does anyone have any idea where I'm gone wrong? Much appreciated!
Try
'----------------Sends the message-------------------------------------
MysqlConn.Open() ' opening the connection to the DB
Dim query As String
query = "insert into dojodb.chats (Message) values ('" & txtMessage.Text & "')"
command = New MySqlCommand(query, MysqlConn)
reader = command.ExecuteReader 'executes the command and reads data from db
reader.Close()
'-------------------Retreives the message------------------------------------
Dim sqlStr As String = "SELECT * FROM chats"
Dim chatcommand As New MySqlCommand(sqlStr, MysqlConn)
Dim rdr As MySqlDataReader = chatcommand.ExecuteReader()
Dim tbl As New DataTable
tbl.Load(rdr)
'-------For every row, print the message, skip a line, and add 1 so it goes to next msg--------
For i As Integer = 0 To tbl.Rows.Count - 1
rowIndex = i
strOutPut &= CStr(tbl.Rows(rowIndex)("Message")) & vbNewLine
i = i + 1
Next
txtGroupChat.Text = strOutPut
strOutPut = "" 'clearing the string so that it does not print out duplicate info next time
'-------------------------End Retrieve-------------------------------------------
MysqlConn.Close()
Catch ex As Exception
MessageBox.Show(ex.Message) 'printing the exact error to help future testing if needed
Finally
MysqlConn.Dispose()
End Try
End Sub
I think your problem is this section:
'-------For every row, print the message, skip a line, and add 1 so it goes to next msg--------
For i As Integer = 0 To tbl.Rows.Count - 1
rowIndex = i
strOutPut &= CStr(tbl.Rows(rowIndex)("Message")) & vbNewLine
i = i + 1
Next
Why are you skipping a line? This will cause every other message in the table to not be written out, and therefore that's why you have to press it twice so that it shows up. You don't need to manually increment the indexer in a For loop, I suggest you try this:
For i As Integer = 0 To tbl.Rows.Count - 1
rowIndex = i
strOutPut &= CStr(tbl.Rows(rowIndex)("Message")) & vbNewLine
Next
How can I convert a row data into string or text and display it into a label? My problem is when I click on my login button which contains the SQL code that gains a row data into alabel, the result in my label is false. not the text. How can I convert it into string?
Here's my code:
Private Sub cmdLog_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdLog.Click
Dim connection As New SqlClient.SqlConnection
Dim command As New SqlClient.SqlCommand
Dim adaptor As New SqlClient.SqlDataAdapter
Dim dataset As New DataSet
Dim reader As MySqlDataReader = Nothing
Dim sapi
sapi = CreateObject("sapi.spvoice")
connection.ConnectionString = ("Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\Calupad\Desktop\HTF feat Yiyet\HTF feat Yiyet\Database1.mdf;Integrated Security=True;User Instance=True")
command.CommandText = "SELECT * FROM [Users] WHERE Username='" & txtUser.Text & "' AND Password ='" & txtPass.Text & "';"
txtWel.Text = "Welcome Back, " + txtUser.Text + "!....."
connection.Open()
command.Connection = connection
adaptor.SelectCommand = command
adaptor.Fill(dataset, "0")
txtStat.text = command.CommandText = "SELECT Status FROM [Users] WHERE Username = '" & txtUser.Text & "' ".ToString
txtStat.Text = stat
Dim count = dataset.Tables(0).Rows.Count
If count > 0 Then
MsgBox("Login Successful!" & vbNewLine & txtStat.Text, MsgBoxStyle.Information, "Access Granted")
sapi.speak(txtWel.Text)
Me.Hide()
Form1.Show()
frmMenu.Show()
txtUser.Clear()
txtPass.Clear()
tries = 3
Else
ctr = tries - 1
tries = ctr
sapi.speak(txtUser.Text + txtNot.Text)
MsgBox("Invalid Account!" + vbNewLine + "Attempts Remaining: " & tries, vbCritical, "Access Denied")
txtUser.Clear()
txtPass.Clear()
If tries = 0 Then
MsgBox("You've reached the maximum attempts!" + vbNewLine + "The program will be terminated.", vbCritical, "Terminated!")
Me.Close()
End If
End If
End Sub
First of all, the way you check for username and password is weak and is most certainly volnurable to SQL injections. You are checking if the 'count' of rows is greater than zero then the user has logged in successfully, where as you should only compare count to 1. and instead of counting the rows, try to compare the row values to what the user has input in the username and passoword fields and what is returned from the database rows.
The "hacker" can simply type this and he will be allowed to log in according to the logic of your code:
You just need to retrieve the data stored into dataset variable that you filled using the adapter.
Assuming your database table contains fields like First_Name and 'Last_Name', here is how you can display them on any label control on your form:
adaptor.Fill(dataset, "0")
myFirstName.Text = dataset.Tables(0).Rows(0).Item("First_Name").ToString()
myLastName.Text = dataset.Tables(0).Rows(0).Item("First_Name").ToString()
You can also retrieve the column without having to know its name like this
myLabel.text = = dataset.Tables(0).Rows(0).Item(3).ToString()
'This will retrieve the 4th column from the table (zero based array)
You can also clean up your code by declaring a variable to hold the retrieved table
adaptor.Fill(dataset, "0")
Dim myTable as DataTable = dataset.Tables(0)
myFirstName.Text = myTable.Rows(0).Item(0).ToString()
Hope this helps
I have created a screen for editing database records. After user selects the table, I have dynamically added Labels and TextBox inside the TableLayoutPanel1. I want to know how to access the value present in the TextBox which is inside TableLayoutPanel1
I code which i used:
Dim strSQL, strSQL1 As String
Dim ln As Integer
Dim reader As OleDbDataReader
Dim connection As OleDbConnection
Dim ds As New DataSet
connection = New OleDbConnection(CONNECT_STRING)
connection.Open()
ln = 0
strSQL = " select * from syscat.columns where TABSCHEMA like 'QA1MM%' and TABNAME like 'SKU_STR_LIST' with ur "
RichTextBox1.Text = RichTextBox1.Text + strSQL
Dim selectCMD As OleDbCommand = New OleDbCommand(strSQL, connection)
reader = selectCMD.ExecuteReader
MessageBox.Show("Column: " & reader(0) & " ")
While reader.Read()
If String.IsNullOrEmpty(reader(0)) Then
Else
TableLayoutPanel1.ColumnCount = 2
TableLayoutPanel1.RowCount = 20
Dim aLabel As New System.Windows.Forms.Label
Dim aTextBox As New System.Windows.Forms.TextBox
aLabel.Name = "New Label"
aLabel.Text = reader(0).Text
TableLayoutPanel1.Controls.Add(aLabel, 0, ln)
TableLayoutPanel1.Controls.Add(aTextBox, 1, ln)
ln = ln + 1
End If
End While
How can i access the value present in the aTextBox which i added dynamically inside the TableLayoutPanel1?
First off you need to set a name on the TextBox. Basically aTextbox.Name = "TextBox1". Then you should be able to find the control by using:
Control c = TableLayoutPanel1.Controls.Find("TextBox1",true)
Keep in mind however that this will give you a control, not a textbox. So typecast it in whatever way you find suitable.
Ctype(c,TextBox)
DirectCast(c,TextBox)
As WozzeC says you need to give the text box a name that is unique, probably something like
aTextBox.Name = "TextBox" & ln
Then you could find it this way
Dim words = TableLayoutPanel1.Controls("Textbox1").Text
or if its in the same loop
Dim words = TableLayoutPanel1.Controls("Textbox" & ln).Text
Thanks everyone for thumbing down my question and not helping me out. This website is amazing.
My program creates columns at runtime with the following code:
Cmd = New OleDb.OleDbCommand("ALTER TABLE [Parent] ADD [" & ColumnDate & "] int", con)
objCmd = New OleDb.OleDbCommand("ALTER TABLE [Parent] ADD [" & ColumnDate & "] int", con)
objCmd.ExecuteNonQuery()
I add data into the newly inserted column with the following code:
da.SelectCommand = New OleDb.OleDbCommand(sql, con)
Dim cb As New OleDb.OleDbCommandBuilder(da)
cb.QuotePrefix = "["
cb.QuoteSuffix = "]"
ds.Tables("SchoolMaticsDatabase").Rows(inc).Item(ColumnDate) = Hours * Num
da.Update(ds, "SchoolMaticsDatabase")
All of the above works fine; the issue arises when I try to edit the information originally placed in the newly added column. These are the approaches that I have taken. (None of them give an error message; it simply won't update within the database.)
Approach 1:
da.SelectCommand = New OleDb.OleDbCommand(sql, con)
Dim cb As New OleDb.OleDbCommandBuilder(da)
cb.QuotePrefix = "["
cb.QuoteSuffix = "]"
For Each column As DataColumn In ds.Tables("SchoolMaticsDatabase").Columns
If IsDate(column.ColumnName) = True Then
ds.Tables("SchoolMaticsDatabase").Rows(inc).Item(column.ColumnName) = DataGridView3.Item(column.ColumnName, 0).Value
End If
Next
da.Update(ds, "SchoolMaticsDatabase")
Approach 2:
da.SelectCommand = New OleDb.OleDbCommand(sql, con)
Dim cb As New OleDb.OleDbCommandBuilder(da)
cb.QuotePrefix = "["
cb.QuoteSuffix = "]"
For count = 13 To MaxColumns - 1
ds.Tables("SchoolMaticsDatabase").Rows(inc).Item(count) = DataGridView3.Item(count, 0).Value
Next
da.Update(ds, "SchoolMaticsDatabase")
Approach 3:
For Each column As DataColumn In ds.Tables("SchoolMaticsDatabase").Columns
If IsDate(column.ColumnName) Then
Cmd = New OleDb.OleDbCommand("UPDATE [Parent] SET [" & column.ColumnName & "]=" & DataGridView3.Item(column.ColumnName, 0).Value & " WHERE [ID]=" & inc + 1, con)
objCmd = New OleDb.OleDbCommand("UPDATE [Parent] SET [" & column.ColumnName & "]=" & DataGridView3.Item(column.ColumnName, 0).Value & " WHERE [ID]=" & inc + 1, con)
objCmd.ExecuteNonQuery()
End If
Next
I added a column to the table manually via opening the access database and all the above approaches work for editing data stored in that column. So I believe it is something to do with the fact that the columns are created at run time.
I suspect that your DataSet (ds) is out of sync.
First, confirm that the new column is present within the DataSet: For any one of your three approaches, put a break-point just before the loop starts, and take a look at ds.Tables("SchoolMaticsDatabase").Columns and confirm that the new column is in fact listed there. Alternatively, put a Debug.Print column.ColumnName inside the loop and look for it in the Output window.
Second, assuming that the new column is in the Columns member, I would recommend making a little project on the side to explore your issue further. Make it simple, nothing fancy. Let it create a column (avoid using dates as names at first), give it a value, update its value, see how it goes.
Good luck!