How can I show a picture on a form in VB.NET? - vb.net

I am creating questionnaires using VB.NET and SQL and my problem now is how can I show an image already present in the database onto a form? Please note that as the form is a questionnaire, it is navigable by the means of going up or down rows in a dataset. For example when the NEXT button is clicked, the row in the dataset goes +1. So how should I go about coding it in order to display an image onto the form?
this is the code how i saved the image
Dim ms As New MemoryStream()
PictureBox1.Image.Save(ms, PictureBox1.Image.RawFormat)
Dim data As Byte() = ms.GetBuffer()
Dim x As New SqlParameter("#image", SqlDbType.Image)
x.Value = data
cmd.Parameters.Add(x)
And the code for navigating between rows of a dataset in a single form:
RichTextBox1.Text = dsquestionnaire.Tables(0).Rows(qsno).Item("Question") .....
qsno + 1 (As a part of the NEXT button click event)
Thanks in advance..

You can load the image from the DB into your picture box as follows:
Using ms As New IO.MemoryStream(CType(row("image", Byte()))
Dim img As Image = Image.FromStream(ms)
Image1.Image = img
For the click event you can place this inside a method and just call it to load the image into the Picture box when the next button is clicked

Related

Check if data exist in file

I need help. I want to check if user exists by entering their ic number and I want to display another rest of their data by using file in visual basic. Unfortunately, an error occurs while doing that. I need help. If the user exists, then It will display automatically name, email, address and so on but if a user doesn't exist, then it shows message box. Here I attached the image of the display screen and the code. Please help me. Thank you.
Public Class Form1
Private Sub btnSearch_Click(sender As Object, e As EventArgs) Handles btnSearch.Click
Dim userFile As String = "C:\Users\HP\Desktop\userdata.txt"
Dim inputFile As String
If System.IO.File.Exists(userFile) = True Then
Dim objReader As New System.IO.StreamReader(userFile)
Dim intIc As Integer
Dim intCount As Integer = 0
Dim strName As String
Dim strEmail As String
Dim intPhoneNum As String
Dim strAdd1 As String
Dim strAdd2 As String
Dim intPostcode As String
Dim strState As String
Do While objReader.Peek() <> -1
intIc(intCount) = Convert.ToInt64(objReader.ReadLine())
If (intIc(intCount).Convert.ToInt64(objReader.ReadLine())) Then
strName(intCount) = objReader.ReadLine()
strEmail(intCount) = objReader.ReadLine()
intPhoneNum(intCount) = Convert.ToInt32(objReader.ReadLine())
strAdd1(intCount) = objReader.ReadLine()
strAdd2(intCount) = objReader.ReadLine()
intPostcode(intCount) = Convert.ToInt32(objReader.ReadLine())
strState(intCount) = objReader.ReadLine()
lblName.Text = strName
lblEmail.Text = strEmail
lblNum.Text = intPhoneNum
lblAdd1.Text = strAdd1
lblAdd2.Text = strAdd2
lblPostcode.Text = intPostcode
lblState.Text = strState
objReader.Close()
Else
MessageBox.Show("User Does Not Exist")
End If
intCount = intCount + 1
Loop
Else
MessageBox.Show("File Does Not Exist")
End If
End Sub
End Class
Your task, the easy way:
make a new project
add a DataSet to this new project
open the DataSet, in the properties call it something sensible
Right click the surface, add a new datatable, name it Person
Right click the datatable, add a column, name it IC. Right click, add column, name it Name. Keep going until you added all the fields you want to track(email,phone,address1 etc)
save the DataSet
open the form
show the datasources window (view menu.. other windows)
expand the nodes til you can see Person
click the drop down next to Person, switch from DataGridview to Details
drag Person onto the form. Text boxes, labels etc appear. In the tray at the bottom more things appear
add a textbox to the form and call it searchTextBox
add a search button to the form, double click it, add this line of code to the click handler:
personBindingSource.Filter = '[ic] LIKE '" & searchTextBox.Text & "'"
If personBindingSource.Count = 0 Then MessageBox.Show("No records")
double click the form background to add a form load event handler, put this line of code:
If IO.File.Exists("data.xml") Then .ReadXml("data.xml")
switch back to designer, single click the form background and switch to event properties of the form, add a handler to the form closing event:
.WriteXml("data.xml")
That's it, you now have a program that will open, read and fill the DataSet with data from the data.xml file, it will search it when you type something in the ic box, the text boxes use databinding to show values automatically, and when you close the program it will save updates data. The only task now is to load the xml file with data.
When the textboxes were added to the form you should also have seen a bar appear across the top with some left/right controls in and a green plus. Click the green plus, type some data in, click it again, type more data. Navigating back, if you're adding new data, will commit the data. If you're looking at existing data, editing it then navigating will commit it
After you added some data, you can search for existing data using the search box. When you've searched for a single value it should be the only thing shown and the nav will show "1 of 1". To get back to the mode where all data is showing, put a single asterisk in the search box and hit search; it should show the number records in the top bar and you can scroll them with the arrows.
If you already have lots of data in a file, like you use in your question, you can read it in a loop (like you do in your question, except don't use that code exactly cos it has loads of errors) as a one time thing and assign it into the datatable, or you can manipulate it directly into being XML in a text editor. This is easy to do if you have a capable text editor but I'll not offer any particular advice on it in case you don't have a large amount of existing data. Ask a new question if you do

how to add captions to a picture programatically

How I Can add some text in pictures automatically?
-- I have a bunch of products and i want to add descriptions and price below of image . And I want to do this job by writing some line of code in vb.net
Because i have more than 2000 images which names is incremental numbers.
Here is a sample image:
sample
Like this image.
U can use(if u don't wanna use a database) a RichTextBox Control
Use this code to add image to the RichTextBox:
'add openfiledial to add image to RichTextBox
img = Image.FromFile(OpenFileDialog1.FileName)
Clipboard.SetImage(img)
Richtextbox1.Paste()
'add some text beneath your image.
Save the richTextBox to file :
Private sub Btn_save_click
'add a saveFileDialogBox
SaveFileDialog1.ShowDialog
Private Sub SaveFileDialog1_DialogResultOk
richTextBox1.SaveFile(saveFiledialog1.FileName, _
RichTextBoxStreamType.RichText)
This is one solution but there are other solutions.Comment if u need them
To load text from file
Richtextbox1.text=file.readalllines(use file location here/openfiledialog.filename)
USING A DATABASE IS THE PERFECT ANSWER
As u said, u have a text file containg the prices...I suggest u to use either MSSQL/ACCESS DATABASE/MYSQL
Now to generate records depending on the text file..Use this(load the textfile in the rtb first)
Dim con as new SqlConnection(Your connectionstring here)
Con.open
Dim cmd as new sqlcommand("Insert into [table name-remove brackets if required](columnname) values("#price")",con)
Dim i as integer
For each line in RichTextbox1.Lines
cmd.parameters.add("#price", sqldbtype.varchar).value=Richtxtbox1.lines(i).text
cmd.executenonquery
Next
Con.close

VB.NET: DataGridViewImageCell - Image from Ressource?

I have added a datagridview on a windows form with the name DataGridView1. The following code adds a row with 2 columns. I want to show an image in the 2nd column.
Dim dt As New DataTable
dt.Columns.Add("TESTROW")
dt.Rows.Add("TESTCONTENT")
DataGridView1.DataSource = dt
Dim colImage As New DataGridViewImageColumn
DataGridView1.Columns.Add(colImage)
For intI As Integer = 0 To dt.Rows.Count
Dim cellImage As New DataGridViewImageCell
' THE FOLLOWING LINE WORKS FINE!!!!
cellImage.Value = Drawing.Image.FromFile("c:\foo\bar.gif")
' BUT WHY NOT THIS?
' cellImage.Value = Properties.Resources.ResourceManager.GetObject("ExistingRessource")
' OR THIS?
' cellImage.Value = CType(Properties.Resources.ResourceManager.GetObject("ExistingRessource"), Image)
cellImage.ImageLayout = DataGridViewImageCellLayout.Zoom
DataGridView1.Rows(intI).Cells(1) = cellImage
Next
It's working fine if I use "fromFile" with the path to the image and the 2nd column shows the gif picture inside the cell.
Unfortunately, my attempt to load an image from the ressource ("GetObject") fails, and the cell shows a page-symbol with a red cross on it.
I got all the images I need inside the ressource.
How can I achieve this?
Thanks in advance.
If you've added an image to the resources, then you can access it with my.resources.ResourceName where ResourceName seems to be "ExistingRessource" in your case
It's possible that your current attempts are failing because the resource isn't actually added properly, or you have got the spelling wrong on the name? Either way if you use my.resources you can see for certain that the resource is added properly.
cellImage.Value = My.Resources.ExistingRessource

How to save data to text file and retrieve

I'm using VB.NET. I am able to load the pics from a folder into a flowlayoutpanel. And then load the clicked picture into a separate picturebox and display the picture's filepath in a label.
Now I want to be able to add rating and description to each of the image in the flowlayoutpanel and save it to a text file in the folder from which the pictures have been loaded. The app should load be able to load the rating and description on the next launch or when the selected image is changed. How do I accomplish this?
You should probably look at accessing the metadata of the pic. This way the info you want is carried with the pic. This is contained in the PropertyItems Class, which is a property of the Image class
Here's a link to an answered question about adding a comment to a jpg. Hope this helps.
Here's an untested conversion of that code in VB.net. You'll probably have to add a reference or 2 and import a couple of namespaces, but syntactically this is correct as near as I can tell.
Public Function SetImageComment(input As Image, comment As String) As Image
Using memStream As New IO.MemoryStream()
input.Save(memStream, Imaging.ImageFormat.Jpeg)
memStream.Position = 0
Dim decoder As New JpegBitmapDecoder(memStream, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.OnLoad)
Dim metadata As BitmapMetadata
If decoder.Metadata Is Nothing Then
metadata = New BitmapMetadata("jpg")
Else
metadata = decoder.Metadata
End If
metadata.Comment = comment
Dim bitmapFrame = decoder.Frames(0)
Dim encoder As BitmapEncoder = New JpegBitmapEncoder()
encoder.Frames.Add(bitmapFrame.Create(bitmapFrame, bitmapFrame.Thumbnail, metadata, bitmapFrame.ColorContexts))
Dim imageStream As New IO.MemoryStream
encoder.Save(imageStream)
imageStream.Position = 0
input.Dispose()
input = Nothing
Return Image.FromStream(imageStream)
End Using
End Function

VB.Net using databindings with a picture box

A row, in a data table, iscalled FirstImage contains a url to an image file on a web server. I am trying to bind the data of this row to the image source of the picture box.
My current code:
For Each row As DataRow In ListData.Rows
Dim ImageDecode = ser.Deserialize(Of PropertyImage())(row("Images"))
row("FirstImage") = "http://rental.joshblease.co.uk/propertyimages/" & ImageDecode(0).Image
'Returns http://rental.joshblease.co.uk/propertyimages/image1.jpg
Next row
TxtListName.DataBindings.Add("Text", ListData, "Name")
TxtListSlug.DataBindings.Add("Text", ListData, "Slug")
TxtListCreated.DataBindings.Add("Text", ListData, "Created")
ImgListItem.DataBindings.Add("Image", ListData, "FirstImage", True)
DataRepeater1.DataSource = ListData
But at the moment, the image is still blank. I have tried entering the location into a hidden textbox and copying the data over, but I can;t figure out how to use the controls in a data repeater.
This was the experimental copy from a hidden text box code:
If Me.DataRepeater1.ItemCount > 0 Then
Dim n As Integer = Me.DataRepeater1.ItemCount
For i As Integer = 1 To n
Me.DataRepeater1.CurrentItemIndex = i - 1
Dim item = Me.DataRepeater1.CurrentItem
item.Controls("ImgListItem").ImageLocation = item.Controls("TxtImageLocation").Text
Next
End If
Simply add Picture Box property ImageLocation
ImgListItem.DataBindings.Add("ImageLocation", ListData, "FirstImage", True)
The databinding for the image expects binary image data and in this case your passing it a string. What we can do is convert the image location into a format the binding can understand. Take a look at this link C# Code Snippet - Download Image from URL. Then once you have the image in memory, you will be able to bind it to your PictureBox.
Also, keep in mind that the simplest way shown in this answer would not work for you since URIs are not supported by the BitMap class.