I have a table tenant in my sql 2005 database. It has the following members, where tdoc and tpic are of datatype image:
tid
tname
tadd
tph
tdoc
tpic
I want to insert 2 images from 2 picture boxes to tdoc and tpic using VB.NET.
I managed to write the following code for my record save button. Please help me with further code.
Private Sub bsave_Click(sender As Object, e As EventArgs) Handles bsave.Click
If ((tname.Text = "") Or (tadd.Text = "") Or (tphn.Text = "")) Then
MsgBox("Details are Incomplete", MsgBoxStyle.Exclamation)
Else
conn.Open()
Dim s As String = "Insert into rent values('" & tid & "','" & tname.Text & "','" & tadd.Text & "','" & tphn.Text & "',#doc,#photo)"
MessageBox.Show("Name & Image has been saved", "Save", MessageBoxButtons.OK)
conn.Close()
End If
End Sub
I would like to use a MemoryStream, please just guide me with it.
I have used this logic in my C# project hope it helps you.
using System.IO;
private void **BrowseFile_Click**(object sender, EventArgs e)
{
OpenFileDialog dlg = new OpenFileDialog();
dlg.Filter = "JPG Files(*.jpg)|*.jpg|PNG Files(*.pnbg)|*.png|All Files(*.*)|*.*";
dlg.Title = " Select Bike Picture";
if (dlg.ShowDialog() == DialogResult.OK)
{
String picLoc = dlg.FileName.ToString();
pictureBox1.ImageLocation = picLoc;
textBox9.Text = picLoc;
}
}
private void **SaveButton_Click**(object sender, EventArgs e)
{
FileStream fs1 =newFileStream(textBox9.Text,System.IO.FileMode.Open, System.IO.FileAccess.Read);
byte[] image = new byte[fs1.Length];
fs1.Read(image, 0, Convert.ToInt32(fs1.Length));
fs1.Close();
con.Open();
SqlCommand cmdupdt = new SqlCommand("Insert into TableName values(#pic )",con);
SqlParameter prm = new SqlParameter("#pic", SqlDbType.VarBinary, image.Length, ParameterDirection.Input, false, 0, 0, null, DataRowVersion.Current, image);
cmdupdt.Parameters.Add(prm);
cmdupdt.ExecuteNonQuery();
con.Close();
}
Related
public void showdata(string pss, string cipherText)
{
SqlConnection conn1 = new SqlConnection(str);
SqlCommand cmd1 = new SqlCommand("update Tbl_Users set Password = '" + pss + "'where Password ='" + cipherText + "'", conn1);
SqlDataAdapter sda1 = new SqlDataAdapter(cmd1);
DataSet ds1 = new DataSet();
sda1.Fill(ds1, "Tbl_Users");
dataGridView1.DataSource = ds1;
dataGridView1.DataMember = ds1.Tables["Tbl_Users"].ToString();
}
Ur Updated Ans
public void showdata(string pss, string cipherText)
{
SqlConnection conn1 = new SqlConnection(str);
> SqlCommand cmd1 = new SqlCommand("**update Tbl_Users set Password = '" +
> pss + "'where Password ='" + cipherText + "'"**, conn1);
It should be select statment not Update Or Inser Statment
SqlDataAdapter sda1 = new SqlDataAdapter(cmd1);
Datatable ds1 = new Datatable ();
sda1.Fill(ds1);
dataGridView1.DataSource = ds1;
}
I'm trying to make a form where the user inputs a SerialNb, clicks on a button, and it shows a new form, containing the remaining columns where Table.SerialNbColumn = SerialNbInput
The error I would get would be "Expression does not produce a value", I'm seriously stuck because, well, it's quite simple, but it should actually present a value.
Dim SQL As New SQLControl
//\\ **** USELESS CODES, ETC...
Dim SynPayForm As New SynPaymentForm
SynPayForm.DateFill = SQL.RunQuery("SELECT aDatePaid FROM SYNPaymentHistory WHERE SerialNb='" & SerialInput.Text & "' ")
SynPayForm.SerialNbFill = SerialInput.Text
SynPayForm.NameFill = SQL.RunQuery("SELECT FullName FROM SYNPaymentHistory WHERE SerialNb='" & SerialInput.Text & "' ")
//\\ ** OTHER COLUMNS THAT HAVE SAME CONCEPT **
SynPayForm.Show()
EDIT: Added SQLControl's functions
Public Class SQLControl
Public SQLCon As New SqlConnection With {.ConnectionString = "Server=HOME\SQLEXPRESS;Database=Project Alpha1;User=sa;Pwd=patrick442;"}
Public SQLCmd As SqlCommand
Public SQLDA As SqlDataAdapter
Public SQLDataset As DataSet
Public Sub RunQuery(Query As String)
Try
SQLCon.Open()
SQLCmd = New SqlCommand(Query, SQLCon)
//\\ LOAD SQL RECORDS FOR DATAGRID
SQLDA = New SqlDataAdapter(SQLCmd)
SQLDataset = New DataSet
SQLDA.Fill(SQLDataset)
SQLCon.Close()
Catch ex As Exception
MsgBox(ex.Message)
If SQLCon.State = ConnectionState.Open Then
SQLCon.Close()
End If
End Try
End Sub
I have a form and I'm wondering is it possible to calculate a specific column in a datagridview and output it to a label with the use of a generate button? If yes how do I go about doing it?
Thanks
(this is how the datagridview is set up)
Private Sub refreshdata()
If Not cnn.State = ConnectionState.Open Then
'open connection
cnn.Open()
End If
'create new data and insert the data, Employee, Firstname, lastname, address etc.
Dim da As New OleDb.OleDbDataAdapter("SELECT employeeno as [EmployeeID], " & _
"firstname as [FirstName], lastname as [LastName], address as [Address], department as [Department], workinghours as [WorkingHours], datehired as [DateHired], contactnumber as [ContactNumber] " & _
"FROM employee ORDER BY EmployeeNo", cnn)
Dim dt As New DataTable
'fill data into datatable
da.Fill(dt)
'offer data to be placed in datagridview
Me.DataGridView1.DataSource = dt
'close connection
cnn.Close()
End Sub`enter code here`
I'm not sure what you want to do. If you want just column header in your textBox try this:
C#
private void button1_Click(object sender, EventArgs e)
{
textBox1.Text = dataGridView1.Columns["columnName"].HeaderText;
}
VB
Private Sub button1_Click(sender As Object, e As EventArgs)
textBox1.Text = dataGridView1.Columns("columnName").HeaderText
End Sub
To place your output inside label simply change textBox1.Text to label1.Text. If you want all data written inside your cells of certain column try this:
C#
private void button1_Click(object sender, EventArgs e)
{
StringBuilder sb = new StringBuilder();
foreach (DataGridViewRow row in dataGridView1.Rows)
{
if (row.IsNewRow)
break;
sb.Append(row.Cells["columnName"].Value + " ");
}
textBox1.Text = sb.ToString();
}
VB
Private Sub button1_Click(sender As Object, e As EventArgs)
Dim sb As New StringBuilder()
For Each row As DataGridViewRow In dataGridView1.Rows
If row.IsNewRow Then
Exit For
End If
sb.Append(row.Cells("columnName").Value + " ")
Next
textBox1.Text = sb.ToString()
End Sub
By the way, column name is the column name in design when you right click your DataGridView > Edit columns under design, there should be a "Name" parameter. Hopefully this covers the answer for your question. Cheers!
EDIT:
Added total sum of column output in textBox solution:
C#
private void button1_Click(object sender, EventArgs e)
{
int sum = 0;
foreach (DataGridViewRow row in dataGridView1.Rows)
{
if (row.IsNewRow)
break;
int number;
if (int.TryParse(row.Cells["columnName"].Value.ToString(), out number))
sum += number;
}
textBox1.Text = sum.ToString();
}
VB
Private Sub button1_Click(sender As Object, e As EventArgs)
Dim sum As Integer = 0
For Each row As DataGridViewRow In dataGridView1.Rows
If row.IsNewRow Then
Exit For
End If
Dim number As Integer
If Integer.TryParse(row.Cells("columnName").Value.ToString(), number) Then
sum += number
End If
Next
textBox1.Text = sum.ToString()
End Sub
I have problem with database save changes:
coon1.ConnectionString = _
"Provider=Microsoft.Jet.OLEDB.4.0;Data source=" & _
"magazyn.mdb"
sql = "INSERT INTO magazyn (ID_Towaru,Kod_Towaru,Nazwa_Towaru,Ilość_w_magazynie,ilość_minimalna,ALERT) VALUES ('" & jakiid & "','" & kodtowaru & "','" & nazwatowaru & "','" & iloscwmagazynie & "','" & iloscminimalna & "',0)"
Dim MyConnection As New OleDbConnection(conn)
Dim command1 As New OleDbCommand(sql, MyConnection)
command1.Connection.Open()
command1.ExecuteNonQuery()
MyConnection.Close()
I try add new record to table magazyn, but when opened database with Access then I didn't see any new record related to magazyn in the table. But ViewGrid shows me this new element until I close and re-open the program.
Does someone know where the problem is?
Always use parameters and not string concatenation. This rule should be followed categorically
sql = "INSERT INTO magazyn " +
"(Kod_Towaru,Nazwa_Towaru,Ilość_w_magazynie,ilość_minimalna,ALERT) " +
"VALUES (?, ?, ?, ?,0)"
Using MyConnection As New OleDbConnection(conn)
Using command1 As New OleDbCommand(sql, MyConnection)
command1.Connection.Open()
command1.Parameters.AddWithValue("#Kod", kodtowaru)
command1.Parameters.AddWithValue("#naz", nazwatowaru)
command1.Parameters.AddWithValue("#ilo", iloscwmagazynie)
command1.Parameters.AddWithValue("#mini", iloscminimalna)
command1.ExecuteNonQuery()
End Using
End Using
This, of course, requires that the variables used as value for the parameters are of the correct datatype.
Please Insert This Below Coding in Module.
Imports System.Data.OleDb
Module Module1
Public OleCn As New OleDbConnection()
Public Function StrConnection() As String
StrConnection = "Provider=Microsoft.Ace.Oledb.12.0; Data Source=" & My.Application.Info.DirectoryPath.ToString() & "\BackUp\Testing.Accdb;"
Return StrConnection
End Function
After This Insert the Below Coding in Save Button.
Dim msg As DialogResult = MessageBox.Show("Do you want to Save this Record? ", "Response", MessageBoxButtons.YesNo, MessageBoxIcon.Question)
If (msg = vbYes) Then
If RequiredEntry() = True Then
Return
End If
Try
With OleCn
If .State <> ConnectionState.Open Then
.ConnectionString = StrConnection()
.Open()
End If
End With
Catch ex As Exception
MessageBox.Show(ex.Message, "Connection Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
Try
Dim sSQL As String = "insert into Vendor values(#VendorCode,#VendorName,#Address,#City,#LandPhone,#Mobile,#EmailID,#Balance)"
Dim cmd As OleDbCommand = New OleDbCommand(sSQL, OleCn)
'VendorCode
Dim VendorCode As OleDbParameter = New OleDbParameter("#VendorCode", OleDbType.VarChar, 10)
VendorCode.Value = txtVendorCode.Text.ToString()
cmd.Parameters.Add(VendorCode)
'VendorName
Dim VendorName As OleDbParameter = New OleDbParameter("#VendorName", OleDbType.VarChar, 25)
VendorName.Value = txtVendorName.Text.ToString()
cmd.Parameters.Add(VendorName)
'Address
Dim Address As OleDbParameter = New OleDbParameter("#Address", OleDbType.VarChar, 50)
Address.Value = txtAddress.Text.ToString()
cmd.Parameters.Add(Address)
'City
Dim City As OleDbParameter = New OleDbParameter("#City", OleDbType.VarChar, 25)
City.Value = txtCity.Text.ToString()
cmd.Parameters.Add(City)
'LandPhone
Dim LandPhone As OleDbParameter = New OleDbParameter("#LandPhone", OleDbType.VarChar, 50)
LandPhone.Value = txtLandPhone.Text.ToString()
cmd.Parameters.Add(LandPhone)
'Mobile
Dim Mobile As OleDbParameter = New OleDbParameter("#Mobile", OleDbType.VarChar, 15)
Mobile.Value = txtMobile.Text.ToString()
cmd.Parameters.Add(Mobile)
'EmailID
Dim EmailID As OleDbParameter = New OleDbParameter("#EmailID", OleDbType.VarWChar, 25)
EmailID.Value = txtEmailID.Text.ToString()
cmd.Parameters.Add(EmailID)
'Balance
Dim Balance As OleDbParameter = New OleDbParameter("#Balance", OleDbType.VarWChar, 10)
Balance.Value = txtBalance.Text.ToString()
cmd.Parameters.Add(Balance)
If cmd.ExecuteNonQuery() Then
OleCn.Close()
MessageBox.Show("New Record is Added Successfully.", "Record Saved")
Call clear()
Else
MsgBox("Record Addition Failed ", MsgBoxStyle.Critical, "Addition Failed")
Return
End If
Catch ex As Exception
MessageBox.Show(ex.Message.ToString(), "Data Error")
Exit Sub
End Try
End If
I am getting an exception when I run the below VB.NET code to validate a user..The exception says that "Incorrect syntax near variable user"
Can anyone tell me where am I going wrong ?
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
If TextBox1.Text.Trim().Length = 0 Or TextBox2.Text.Trim().Length = 0 Then
MsgBox("Enter a user id and password")
Return 'Terminate this method
End If
Dim myconnection As SqlConnection
Dim mycommand As SqlCommand
Dim dr As SqlDataReader
Dim userid = TextBox1.Text
Dim password = TextBox2.Text
Try
myconnection = New SqlConnection("server=PARTH- PC\SQLEXPRESS;uid=sa;pwd=parth;database=fcrit")
myconnection.Open()
mycommand = New SqlCommand("select * from user where [user id]=#userid and [password]=#password", myconnection)
mycommand.Parameters.Add("#userid", SqlDbType.VarChar, 30).Value = userid
mycommand.Parameters.Add("#password", SqlDbType.VarChar, 30).Value = password
'mycommand = New SqlCommand("select * from user where user id='" & TextBox1.Text & "' and password='" & TextBox2.Text & "'", myconnection)
dr = mycommand.ExecuteReader()
If (dr IsNot Nothing) Then
If (dr.Read()) Then
MsgBox("User is authenticated")
Form2.Show()
Else
MsgBox("Please enter correct username and password")
End If
End If
myconnection.Close()
Catch ex As Exception
Throw
Finally
End Try
End Sub
Try changing your SQL to -
"select * from [user] where [user id]=#userid and [password]=#password"
According to this page 'User' is a reserved word
User is a reserved word in SQL Server.
Put brackets around the table name:
mycommand = New SqlCommand("select * from [user] where [user id]=#userid and [password]=#password", myconnection)