get picture from database(close) - vb.net

this is my success code:
Private Sub dg1_CellClick(sender As Object, e As DataGridViewCellEventArgs) Handles dg1.CellContentClick
Label5.Text = dg1.Item(0, e.RowIndex).Value
Label6.Text = dg1.Item(2, e.RowIndex).Value
con.ConnectionString = "Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\USERS\USER\DOWNLOADS\SDP(BACKUP1)\SDP(BACKUP)\SDP.MDF;Integrated Security=True"
con.Open()
cmd.Connection = con
cmd.CommandText = "select picture from Announcement where name = #name"
cmd.Parameters.AddWithValue("#name", dg1.CurrentRow.Cells(0).Value())
da.SelectCommand = cmd
Dim imageData As Byte() = DirectCast(cmd.ExecuteScalar(), Byte())
If Not imageData Is Nothing Then
Using ms As New MemoryStream(imageData, 0, imageData.Length)
ms.Write(imageData, 0, imageData.Length)
PictureBox2.Image = Image.FromStream(ms, True)
End Using
End If
End Sub
i had success get my picture from database. which add paramater to name, then parameter name with #name.

You're not loading a picture from a DataGridView at all. You're trying to query a database and it's failing. Nothing to do with grids or images. Plain and simple, you've written bad SQL code. If you're going to include a text literal then it needs to have single quotes around it. Better still, do it properly and use parameters.
The issue is, as I have said, in your SQL code:
cmd.CommandText = "select picture from Announcement where name =" & dg1.Item(0, e.RowIndex).Value & ""
You are inserting a value for the name column into that SQL code so it becomes text literal. As I said, text literals require single quotes. Where are your single quotes? You don't have any. That's the issue. If you were going to use string concatenation like that, which you should not, then it would need to look like this:
cmd.CommandText = "select picture from Announcement where name = '" & dg1.Item(0, e.RowIndex).Value & "'"
If you were to do it properly, which involves using parameters, as I said, then it would look something like this:
cmd.CommandText = "select picture from Announcement where name = #name"
cmd.Parameters.AddWithValue("#name", CStr(dg1.Item(0, e.RowIndex).Value))
or like this:
cmd.CommandText = "select picture from Announcement where name = #name"
cmd.Parameters.Add("#name", SqlDbType.VarChar, 50).Value = CStr(dg1.Item(0, e.RowIndex).Value)

Related

how to get datatable if textbox matches your data in database

how can I possibly populate my table if like textbox.text matches from my data inside database.
I'm stuck here, not sure where I did go wrong
Private Sub Button6_Click(sender As Object, e As EventArgs) Handles Button6.Click
Dim dbcommand As String
dbcommand = "SELECT * FROM aws_rdp where csn_user like " & txtCSNUser.Text & ""
adt = New OleDbDataAdapter(dbcommand, dbconn)
datatable = New DataTable
adt.Fill(datatable)
DataGridView1.DataSource = datatable
End Sub
Try putting ' before and after the quotation marks surrounding the textbox text. If you're trying to find that text within the text stored in the database you will also need wildcards (%) surrounding it too. Try:
dbcommand = "SELECT * FROM aws_rdp where csn_user like '%" & txtCSNUser.Text & "%'"
Also, as others have stated, look into using parameters in your SQL code as it will help prevent things like SQL injection and is always good practice
Found the answer to my problem by using this code. Anyways, thanks for your time replying on my query, will surely take note of your advises for my future references
Dim dbcommand As String = "SELECT * FROM aws_rdp where csn_user like '%" & txtCSNUser.Text & "%'"
Dim command As New OleDbCommand(dbcommand, dbconn)
Dim adapter As New OleDbDataAdapter(command)
Dim datatable As New DataTable
adapter.Fill(datatable)
DataGridView1.DataSource = datatable
DataGridView1.Columns(0).HeaderText = "ID"
DataGridView1.Columns(1).HeaderText = "IP Address"
DataGridView1.Columns(2).HeaderText = "Username"
DataGridView1.Columns(3).HeaderText = "Password"

Error on Search Button

I searched on some codes on how to do a Search Button in VB.net. But somehow, it won't work because of an error. And simply because, I cannot understand its algorithm and function. Newbie here. Anyway, here is the code for the search button:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
myConnection.Open()
crd.Clear()
fn.Clear()
ln.Clear()
Dim str As String
str = "SELECT * FROM tblReg WHERE (Code = '" & src.Text & "')"
Dim cmd As OleDbCommand = New OleDbCommand(str, myConnection)
dr = cmd.ExecuteReader
While dr.Read()
crd.Text = dr("crd").ToString
fn.Text = dr("fName").ToString
ln.Text = dr("lName").ToString
End While
myConnection.Close()
End Sub
And the error was on:
dr = cmd.ExecuteReader
And VB said:
An unhandled exception of type 'System.Data.OleDb.OleDbException' occurred in System.Data.dll
Additional information: No value given for one or more required parameters.
One should not follow online tutorials that teach very bad code. That code is very bad because it contains SQL injection and leaves database objects opened.
You should rewrite your code as follows:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
myConnection.Open()
crd.Clear()
fn.Clear()
ln.Clear()
Using cmd = New OleDbCommand("SELECT * FROM tblReg WHERE Code = ?", myConnection)
cmd.CommandType = CommandType.Text
With cmd.Parameters.Add(Nothing, OleDbType.VarChar, 50)
.Direction = ParameterDirection.Input
.Value = src.Text
End With
Using dr = cmd.ExecuteReader()
While dr.Read()
crd.Text = dr("crd").ToString
fn.Text = dr("fName").ToString
ln.Text = dr("lName").ToString
End While
End Using
End Using
myConnection.Close()
End Sub
You have to use question marks in place of parameters because you are using OleDbCommand that does not support named parameters.
Change OleDbType.VarChar to your actual column type.
Is this the link where you get the code?
http://www.visual-basic-tutorials.com/ReadFromAccess.htm
Kindly do not get the code read each data on the output shows and also check this part of the code.
crd.Text = dr("crd").ToString
fn.Text = dr("fName").ToString
ln.Text = dr("lName").ToString
are you sure crd,fname,lname are the name of your fields in your table? pls check it and also what is the field type of code? is it a text or INT that is Auto Increment? or just an INT? no matter what it is change your code.
from
str = "SELECT * FROM tblReg WHERE (Code = '" & src.Text & "')"
to
str = "SELECT * FROM tblReg WHERE Code =" & src.Text
Updated
I suggest better read or follow the whole instruction based on link where you get your code. I suggest do the same as what the link said create the same and when the program runs with no error then incorporate it with your program beacuse I tried it using VB.NET and Access and it worked Im sure you dont read it. Do this and Im sure you will not just get the code you need you will also learn.

Search multiple results from database and display in single textbox

guys i want to build an efficient searching tool in vb to search data from my database in mysql where i have stored paragraphs of some information. i want the search to return multiple results like google does but in a textbox in the form of 2-3 paragraphs of the same concept.Also to make the search more efficient i want to include the substring feature that is the % sign in the select query. can anyone tell me how to implement these two features ? here is my basic search code that returns just a single paragraph stored in the table into my result textbox that i hide first and then show when the results appear.
If TextBox1.Text = "" Then
MsgBox("Please Enter a Keyword")
Else
Dim conn As MySqlConnection
conn = New MySqlConnection
conn.ConnectionString = "Server=localhost;UserID=root;Password=admin674;Database=db1"
Dim myadapter As New MySqlDataAdapter
conn.Open()
Dim sqlquery = "select text from text where name like '" & TextBox1.Text & "'"
Dim mycommand As New MySqlCommand
mycommand.Connection = conn
mycommand.CommandText = sqlquery
myadapter.SelectCommand = mycommand
Dim mydata As MySqlDataReader
mydata = mycommand.ExecuteReader
If mydata.HasRows = 0 Then
MsgBox("Data Not Found")
TextBox1.Clear()
TextBox2.Clear()
Else
mydata.Read()
TextBox2.Text = mydata.Item("text")
TextBox2.Show()
End If
You already answered one question yourself - how to do a substring search, simple add % to your query:
Dim sqlquery = "select text from text where name like '%" & TextBox1.Text & "%'"
(ideally, instead of supplying search value in-line you would use parametrized query, which, among other things would help avoid SQL Injection.
As for the second part - you are already using DataReader, all you have to do is instead using a single mydata.Read() command - loop thru all its results. Replace
mydata.Read()
TextBox2.Text = mydata.Item("text")
TextBox2.Show()
with
Dim sb as New StringBuilder()
While mydata.Read()
sb.AppendLine(mydata("text"))
End While
TextBox2.Text = sb.ToString()
TextBox2.Show()
This approach uses StringBuilder class which is an efficient way to concatenate multiple strings.
P.S. Don't forget to close your DataReader and Connection after use.

Syntax error in VB.NET application using SQL

Hi I have been learning VB.NET for about a month now. I am stuck on something I get an error message saying
Syntax error in union query.
The code in question is this.
Private Sub Button5_Click_1(sender As Object, e As EventArgs) Handles Button5.Click
Dim Builder As New OleDb.OleDbConnectionStringBuilder With
{
.Provider = "Microsoft.ACE.OLEDB.12.0",
.DataSource = IO.Path.Combine(Application.StartupPath, "C:\Users\Nige\Documents\Visual Studio 2012\Projects\MS_Access_SimplePassword\bin\Debug\Database1.mdb"),
.PersistSecurityInfo = True
}
LoginForm.txtUserName.Text = LoginForm.txtUserName.Text
If LoginForm.txtUserName.Text <> "" Then
End If
'do what you want to do
lblName.Text = LoginForm.txtUserName.Text
If lblName.Text = LoginForm.txtUserName.Text Then
Builder.Add("Jet OLEDB:Database Password", "password")
Using con As New OleDb.OleDbConnection With {.ConnectionString = Builder.ConnectionString}
Using cmd As New OleDb.OleDbCommand With
{
.Connection = con,
.CommandText =
<SQL>
("SELECT * FROM tblContacts WHERE number" = '55')
Identifier,
UserName,
UserPassword,
UserTimer
FROM tblContacts
</SQL>.Value
}
con.Open()
Dim Reader As OleDb.OleDbDataReader = cmd.ExecuteReader
If Reader.HasRows Then
Reader.Read()
TextBox1.Text = Reader.GetInt32(0).ToString
TextBox2.Text = Reader.GetString(1)
TextBox3.Text = Reader.GetString(2)
TextBox4.Text = Reader.GetString(3)
End If
End Using
End Using
End If
End Sub
The code above was supposed to when I click button5 search my "ms access database" called "tblContacts" for a row that references the number "55"
If my code looks strange in places it because I am a still on a learning path :)
Cheers
I can see a couple of errors in your code above:
Dim Builder As New OleDb.OleDbConnectionStringBuilder With
{
.Provider = "Microsoft.ACE.OLEDB.12.0",
.DataSource = "C:\Users\Nige\Documents\Visual Studio 2012\Projects\MS_Access_SimplePassword\bin\Debug\Database1.mdb"),
.PersistSecurityInfo = True
}
That Path.Combine with two absolute filename is logically wrong, but, nevertheless it works because Path.Combine is able to recognize that the two strings passed are two full filename and thus doesn't try to create an impossible path, but return directly the second string.
From MSDN on Path.Combine
The combined paths. If one of the specified paths is a zero-length
string, this method returns the other path. If path2 contains an
absolute path, this method returns path2.
Then, looking at your query, it clearly an invalid text for a select and thus you get the Syntax Error.
This could be the correct way to query the datatable assuming
You search for a row with a column named 'number'
This column is of text type text
One or more rows contains in this column a text equals to '55'
Dim sqlText = "SELECT Identifier, UserName, UserPassword, UserTimer " +
"FROM tblContacts WHERE number = '55'";
Using con = New OleDb.OleDbConnection(Builder.ConnectionString)
Using cmd = New OleDb.OleDbCommand(sqlText, con)
con.Open()
Using Reader = cmd.ExecuteReader
While Reader.Read()
TextBox1.Text = Reader.GetInt32(0).ToString
TextBox2.Text = Reader.GetString(1)
TextBox3.Text = Reader.GetString(2)
TextBox4.Text = Reader.GetString(3)
End While
End Using
End Using
End Using

The parameterized query expects the parameter which was not supplied

I'm having a problem with my code:
Private Sub TextBox2_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox2.TextChanged
list.Items.Clear()
cmd.CommandText = "SELECT * FROM borrow where (Department LIKE '%" & TextBox2.Text & "%')"
cmd.Connection = con
cmd.CommandType = CommandType.Text
con.Open()
rd = cmd.ExecuteReader()
If rd.HasRows = True Then
While rd.Read()
Dim listview As New ListViewItem
listview.Text = rd("ID").ToString
listview.SubItems.Add(rd("Department").ToString)
listview.SubItems.Add(rd("Purpose").ToString)
listview.SubItems.Add(rd("Items_Details").ToString)
listview.SubItems.Add(rd("Requested_by").ToString)
listview.SubItems.Add(rd("Approved_by").ToString)
listview.SubItems.Add(rd("Date").ToString)
listview.SubItems.Add(rd("Status").ToString)
listview.SubItems.Add(rd("Date_Returned").ToString)
list.Items.Add(listview)
End While
End If
con.Close()
Once I typed in the string in the textbox to search for an item I get this error:
The parameterized query '(#Parameter1 nvarchar(4000))SELECT * FROM
borrow where (Departme' expects the parameter '#Parameter1', which was
not supplied.
Can anyone help me?
If you pass null value to parameter,you will get this error even after you add the parameter
so try to check the value and if it null then use DBNull.Value
This will work
cmd.Parameters.Add("#Department", SqlDbType.VarChar)
If (TextBox2.Text = Nothing) Then
cmd.Parameters("#Department").Value = DBNull.Value
Else
cmd.Parameters("#Department").Value = TextBox2.Text
End If
This will convert the null values from the object layer to DBNull values that are acceptable to the database.
Your website is in serious danger of being hacked.
Read up on SQL Injection and how to prevent it in .NET
Your query problem is the least of your concerns right now.
But.....
#Misnomer's solution is close but not quite there:
Change your query to this:
cmd.CommandText = "SELECT * FROM borrow where (Department LIKE '%#DepartmentText%')"
and add parameters this way (or the way that #Misnomer does):
cmd.Parameters.AddWithValue("#DepartmentText",TextBox2.Text)
The important difference is that you need to change your CommandText.
Building on and simplifying ravidev's answer:
The VB.NET shorthand is:
cmd.Parameters.AddWithValue("#Department", IF(TextBox2.Text, DBNull.Value))
The C# shorthand is:
cmd.Parameters.AddWithValue("#Department", (object)TextBox2.Text ?? DBNull.Value)
Try adding parameters like this -
cmd.Parameters.Add("#Department", SqlDbType.VarChar)
cmd.Parameters("#Department").Value = TextBox2.Text
and change your command text to what #Abe Miessler does he is right i just thought you will figure it out.
If you are writing from a DataGridView control to your database, make sure there is no empty row. Set 'Allow User to add Rows' to false; it truncates the unnecessary last empty row.
SqlConnection conn = new SqlConnection(connectionString);
conn.Open();
//SelectCustomerById(int x);
comboBoxEx1.Items.Clear();
SqlCommand comm = new SqlCommand("spSelectCustomerByID", conn);
//comm.Parameters.Add(new SqlParameter("cust_name", cust_name));
//comm.CommandText = "spSelectCustomerByID";
comm.Parameters.Add(new SqlParameter("cust_id", SqlDbType.Int));
comm.CommandType = CommandType.StoredProcedure;
comm.ExecuteNonQuery();
SqlDataAdapter sdap = new SqlDataAdapter(comm);
DataSet dset = new DataSet();
sdap.Fill(dset, "cust_registrations");
if (dset.Tables["cust_registrations"].Rows.Count > 0)
{
comboBoxEx1.Items.Add("cust_registrations").ToString();
}
comboBoxEx1.DataSource = dset;
comboBoxEx1.DisplayMember = "cust_name";