Sending updates from datagridview to existing row in database - vb.net

I am retrieving records from a database with the following code.
Dim SearchID As Integer = teacherID
Dim NewStudentID As Integer = studentID
Dim DisplayTable As New DataTable()
Dim da As New OleDbDataAdapter()
Dim sqlquery As String = ("select * from tblAppointments WHERE TeacherID =" & teacherID & "")
If conn.State = ConnectionState.Closed Then
conn.Open()
End If
Try
da.SelectCommand = New OleDbCommand(sqlquery, conn)
da.Fill(Finalds, "Display")
DisplayTable = Finalds.Tables("Display")
DisplayTable.Columns.Remove("Instrument")
DisplayTable.Columns.Remove("Room")
DisplayTable.Columns.Remove("TeacherID")
Registersgridview.DataSource = DisplayTable
Registersgridview.Columns(0).Visible = False
conn.Close()
Catch ex As Exception
MsgBox("There are no appointments in the database for " + Tutorcombox.Text)
End Try
It also there then added to a datagridview and certain columns are removed and some are hidden aswell.
Because its essentially a register, when the use clicks on the datagridview field that is a boolean it changes from false to true. I have been trying to send this back to the database, but have had no luck. I have tried the following :
Dim dt As DataTable = New DataTable("SendTable")
Dim row As DataRow
dt.Columns.Add("appID", Type.GetType("System.Int32"))
dt.Columns.Add("Present", Type.GetType("System.Boolean"))
For i = 0 To Registersgridview.Rows.Count - 1
row = dt.Rows.Add
row.Item("appID") = Registersgridview.Rows(i).Cells(0)
row.Item("Present") = Registersgridview.Rows(i).Cells(5)
Next
If conn.State = ConnectionState.Closed Then
conn.Open()
End If
Dim sqlquery As String = "Update tblAppointments SET Present = #Present WHERE appID = #appID"
Dim sqlcommand As New OleDbCommand
For Each newrow As DataRow In dt.Rows
With sqlcommand
.CommandText = sqlquery
.Parameters.AddWithValue("#Present", newrow.Item(1))
.Parameters.AddWithValue("#appID", newrow.Item(0))
.ExecuteNonQuery()
End With
conn.Close()
Next
But have had no luck with doing so, as it crashes without an error.
Can anyone help?

I solved the problem myself, if any of you are having similar problems here is the solution
Dim dt As DataTable = New DataTable("SendTable")
Dim row As DataRow
dt.Columns.Add("appID", Type.GetType("System.Int32"))
dt.Columns.Add("Present", Type.GetType("System.Boolean"))
For i = 0 To Registersgridview.Rows.Count - 1
Dim appID As Integer = Registersgridview.Rows(i).Cells(0).Value
Dim present As Boolean = Registersgridview.Rows(i).Cells(4).Value
row = dt.Rows.Add
row.Item("appID") = appID
row.Item("Present") = present
Next
If conn.State = ConnectionState.Closed Then
conn.Open()
End If
Dim sqlquery As String = "UPDATE tblAppointments SET Present = #Present WHERE appID = #appID"
Dim sqlcommand As New OleDbCommand
For Each newrow As DataRow In dt.Rows
With sqlcommand
.CommandText = sqlquery
.Parameters.AddWithValue("#Present", newrow.Item(1))
.Parameters.AddWithValue("#appID", newrow.Item(0))
.Connection = conn
.ExecuteNonQuery()
End With
Next
conn.Close()
Registersgridview.DataSource = Nothing
dt.Clear()

try this:
Dim dt As DataTable = New DataTable("SendTable")
Dim row As DataRow
dt.Columns.Add("appID", Type.GetType("System.Int32"))
dt.Columns.Add("Present", Type.GetType("System.Boolean"))
For i = 0 To Registersgridview.Rows.Count - 1
row = dt.Rows.Add
row.Item("appID") = Registersgridview.Rows(i).Cells(0)
row.Item("Present") = Registersgridview.Rows(i).Cells(5)
Next
If conn.State = ConnectionState.Closed Then
conn.Open()
End If
Dim sqlquery As String = "Update tblAppointments SET Present = #Present WHERE appID = #appID"
Dim sqlcommand As New OleDbCommand
For Each newrow As DataRow In dt.Rows
With sqlcommand
.CommandText = sqlquery
.Parameters.AddWithValue("#Present", newrow.Item(5))
.Parameters.AddWithValue("#appID", newrow.Item(0))
.ExecuteNonQuery()
End With
conn.Close()
Next

Related

How to check if byte is null vb.net

I'm assigning background images to every button according to my SQL Server database. If a byte is null I get this error:
Unable to cast object of type 'System.DBNull' to type 'System.Byte[]'.
I want to allow buttons with no background images, but the error is preventing me.
Here is what I attempted:
Dim strsql As String
Dim ImgSql() As Byte
Using con As New SqlConnection("constring")
con.Open()
strsql = "SELECT Imagen FROM Inventario WHERE ID=#ID"
Dim cmd As New SqlCommand(strsql, con)
ItemID = 1
cmd.Parameters.Add("#ID", SqlDbType.VarChar).Value = ItemID
Dim myreader As SqlDataReader
myreader = cmd.ExecuteReader
myreader.Read()
ImgSql = myreader("Imagen")
If ImgSql IsNot Nothing AndAlso ImgSql.Length > 0 Then
Dim ms As New MemoryStream(ImgSql)
btn1.BackgroundImage = Image.FromStream(ms)
con.Close()
Else
'do nothing
End If
End Using
Dim ItemID As Integer = 1
Dim sql As String = "SELECT Imagen FROM Inventario WHERE ID=#ID"
Using con As New SqlConnection("constring"), _
cmd As New SqlCommand(sql, con)
cmd.Parameters.Add("#ID", SqlDbType.Integer).Value = ItemID
con.Open()
Using myreader As SqlDataReader = cmd.ExecuteReader()
If myreader.Read() AndAlso Not DBNull.Value.Equals(myreader("Imagen")) Then
Dim ImgSql() As Byte = DirectCast(myreader("Imagen"), Byte())
Using ms As New MemoryStream(ImgSql)
btn1.BackgroundImage = Image.FromStream(ms)
End Using
End If
End Using
End Using
Based on this answer in C#, converted to vb.net and added NULL check
Using con As New SqlConnection("constring")
Using cmd = con.CreateCommand()
cmd.CommandText = "SELECT Imagen FROM Inventario WHERE ID=#ID"
Dim ItemID = 1
cmd.Parameters.AddWithValue("#ID", ItemID)
con.Open()
Dim res = cmd.ExecuteScalar()
If res IsNot Nothing Then
ImgSql = CType(res, Byte())
If ImgSql IsNot Nothing AndAlso ImgSql.Length > 0 Then
Dim ms As New MemoryStream(ImgSql)
btn1.BackgroundImage = Image.FromStream(ms)
End If
End If
End Using
End Using

How to add dynamic Data in to the datagridviewcombobox column?

I am Developing VB.net application.
In that application I take DataGirdView to display data.
I took DataSource property of the datagridview to display 3 columns' data directly from database.
After those columns I add another DataGridViewComboBoxColumn. Then I a want to add dynamic the data into that ComboBoxColumn.
how to do this?
Private Function CreatComboBoxWithEnum() As DataGridViewComboBoxColumn
Dim combo As New DataGridViewComboBoxColumn()
Sqlconn = New SqlConnection
Sqlconn.ConnectionString = "server=.\SQLEXPRESS_2005;Initial Catalog=MachineShopScheduling ;Integrated Security=SSPI;"
Dim adpter As New SqlDataAdapter
Dim ds As New DataTable
Try
Sqlconn.Open()
Dim Query As String
For Each dr As DataGridViewRow In DataGridView1.Rows
Dim val As String = dr.Cells("SrDataGridViewTextBoxColumn").Value.ToString
Query = "select OperationNo from RoutingCalculation where Sr ='" & val & "' "
COMMAND = New SqlCommand(Query, Sqlconn)
adpter.SelectCommand = COMMAND
adpter.Fill(ds)
combo.DataSource = ds
combo.DataPropertyName = "OperationNo"
combo.Name = "OperationNo"
OperationNo.ValueMember = "OperationNo"
OperationNo.DisplayMember = "OperationNo"
Next
Sqlconn.Close()
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
Return combo
End Function
Private Sub load_operationNo()
Sqlconn = New SqlConnection
Sqlconn.ConnectionString = "server=.\SQLEXPRESS_2005;Initial Catalog=MachineShopScheduling ;Integrated Security=SSPI;"
Try
op.Name = "OperationNo"
DataGridView1.Columns.Add(op)
Sqlconn.Open()
Dim Query As String
Dim i As Integer = 0
For Each dr As DataGridViewRow In DataGridView1.Rows
Dim OPno As New DataGridViewComboBoxCell
With OPno
Dim adpter As New SqlDataAdapter
Dim dt As New DataTable
Dim val As String = dr.Cells("SrDataGridViewTextBoxColumn").Value.ToString
Query = "select OperationNo from RoutingCalculation where Sr = " & val & " order by sr"
Using cmd As New SqlCommand(Query, Sqlconn)
adpter.SelectCommand = cmd
adpter.Fill(dt)
End Using
.DataSource = dt
.ValueMember = "OperationNo"
.DisplayMember = "OperationNo"
DataGridView1.Rows(i).Cells("OperationNo") = OPno
i = i + 1
End With
Next
Sqlconn.Close()
Catch ex As Exception
'MessageBox.Show(ex.Message)
End Try
End Sub
This is the code to add dynamically add the data into DatagridViewComboboxColumn

i want to use transaction with my code in VB.NET

I am using SqlDataAdapter and SqlCommandBuilder to insert and update, and I want to use transaction to insert into two tables with this way but I have tried a lot and I didn't succeed
thanks
Dim sql = "select * from ReceiptOfItems where receiptCode=N'" & receiptCode.Text & "' "
Dim dta As New SqlClient.SqlDataAdapter(sql, con)
Dim ds As New DataSet
dta.Fill(ds)
Dim dt As DataTable
dt = ds.Tables(0)
If dt.Rows.Count > 0 Then
' MsgBox("اسم االتصنيفل او رقمه موجود مسبقا ", MsgBoxStyle.Exclamation, "رسالة تنبيه")
receiptCode.Text = Format(Val(GetLastRecord("ReceiptOfItems", "receiptcode")) + 1, "REC0000000")
End If
Dim dr = dt.NewRow
dr!receiptCode = receiptCode.Text
dr!receiptDate = Format(receiptDate.Value, "yyyy/MM/dd")
' dr!receiptDate = receiptDate.Text
dr!supplierCode = GetsupplierCode(supplierName.Text)
dr!SupplierInvoiceCode = SupplierInvoiceCode.Text
dr!supplierInvoiceDate = Format(supplierInvoiceDate.Value, "yyyy/MM/dd")
'dr!supplierInvoiceDate = supplierInvoiceDate.Text
dr!TotalDiscount = Val(TotalDiscount.Text)
dr!TotalReceipt = Val(TotalReceipt.Text)
dr!TotalArabic = TotalArabic.Text
dr!SupplierInvoiceType = SupplierInvoiceType.Text
dr!salesTax = Val(salesTax.Text)
dr!note = note.Text
dr!status = True
dt.Rows.Add(dr)
Dim cmd As New SqlCommandBuilder(dta)
This should work for you:
con.Open()
Dim trans As SqlTransaction = con.BeginTransaction()
Try
Dim insertStr As String = "insert into ReceiptOfItems (receiptCode, receiptDate, etc.) values(#receiptCode, #receiptDate, #etc)"
Dim insertCmd As New SqlCommand(insertStr, con, trans)
For Each dc As DataColumn In dt.Columns
Dim param As New SqlParameter()
param.ParameterName = dc.ColumnName
param.SourceColumn = dc.ColumnName
insertCmd.Parameters.Add(param)
Next
dta.InsertCommand = insertCmd
dta.Update(ds)
trans.Commit()
con.Close()
Catch ex As Exception
trans.Rollback()
End Try
The DataAdapter class has an UpdateCommand and a DeleteCommand property which must be built appropriately if you are doing something other than inserting new rows.

Error: No data exists for the row/column

I get the following error: No data exists for the row/column.
It should retrieve the image
sSql = "SELECT TOP 1 * FROM Attendance ORDER BY Attendance_id DESC"
Dim cmd As New OleDbCommand(sSql, con)
Dim dr As OleDbDataReader = cmd.ExecuteReader()
dr.Read()
lab1id.Text = dr.GetValue(1).ToString
lab1fname.Text = dr.GetValue(2).ToString
lab1lname.Text = dr.GetValue(3).ToString
lab1position.Text = dr.GetValue(4).ToString
lab1subject.Text = dr.GetValue(5).ToString
dr.Close()
sSql = "select Pfile from Faculty where StId = '" & lab1id.Text & "'"
Dim pcmd As New OleDbCommand(sSql, con)
Dim pdr As OleDbDataReader = cmd.ExecuteReader()
pdr.Read()
Dim bits As Byte() = CType(dr("Pfile"), Byte())
Dim memo As New MemoryStream(bits)
Dim myimg As New Bitmap(memo)
imgRetrieve.Image = myimg
pdr.Close()
The dr.GetValue(N) is zero-based ordinal. Change your indices:
While dr.Read()
lab1id.Text = dr.GetValue(0).ToString
lab1fname.Text = dr.GetValue(1).ToString
lab1lname.Text = dr.GetValue(2).ToString
lab1position.Text = dr.GetValue(3).ToString
lab1subject.Text = dr.GetValue(4).ToString
End While
While pdr.Read() ' | you got a typo here. Change `dr` to `pdr`.
Dim bits As Byte() = CType(pdr("Pfile"), Byte())
Dim memo As New MemoryStream(bits)
Dim myimg As New Bitmap(memo)
imgRetrieve.Image = myimg
End While
Consider changing your code to something like this:
Using command As OleDbCommand = con.CreateCommand()
command.CommandText = "SELECT TOP 1 * FROM Attendance ORDER BY Attendance_id DESC;"
Using reader As OleDbDataReader = command.ExecuteReader()
While reader.Read()
lab1id.Text = reader.Item("id").ToString
lab1fname.Text = reader.Item("fname").ToString
lab1lname.Text = reader.Item("lname").ToString
lab1position.Text = reader.Item("position").ToString
lab1subject.Text = reader.Item("subject").ToString
End While
End Using
End Using
Using command As OleDbCommand = con.CreateCommand()
command.CommandText = "select Pfile from Faculty where StId = #StId;"
command.Parameters.AddWithValue("#StId", lab1id.Text)
Using reader As OleDbDataReader = command.ExecuteReader()
While reader.Read()
Dim bits As Byte() = CType(reader.Item("Pfile"), Byte())
Using stream As New MemoryStream(bits)
imgRetrieve.Image = Bitmap.FromStream(stream)
End Using
End While
End Using
End Using
The problem is you never execute pcmd, see the following two lines:
Dim pcmd As New OleDbCommand(sSql, con)
Dim pdr As OleDbDataReader = cmd.ExecuteReader() ' cmd should be replaced with pcmd
I would suggest adding While...End While Statement when getting the values from dr and pdr. You also need to parameterize the second query to avoid SQL Injection.
sSql = "SELECT TOP 1 * FROM Attendance ORDER BY Attendance_id DESC"
Dim cmd As New OleDbCommand(sSql, con)
Dim dr As OleDbDataReader = cmd.ExecuteReader()
While dr.Read()
lab1id.Text = dr.GetValue(1).ToString
lab1fname.Text = dr.GetValue(2).ToString
lab1lname.Text = dr.GetValue(3).ToString
lab1position.Text = dr.GetValue(4).ToString
lab1subject.Text = dr.GetValue(5).ToString
End While
dr.Close()
sSql = "select Pfile from Faculty where StId = #StId"
Dim pcmd As New OleDbCommand(sSql, con)
pcmd.Parameters.AddWithValue("#StId", lab1id.Text)
Dim pdr As OleDbDataReader = pcmd.ExecuteReader()
While pdr.Read()
Dim bits As Byte() = CType(dr("Pfile"), Byte())
Dim memo As New MemoryStream(bits)
Dim myimg As New Bitmap(memo)
imgRetrieve.Image = myimg
End While
pdr.Close()

Using SQLDataReader instead of recordset

I am new to this and had this question. Can I use SQLDataReader instead of a Recordset. I want to achieve the following result in an SQLDataReader.
Dim dbConn As New ADODB.Connection
Dim rs As New ADODB.Recordset
Dim sqlstr As String = "SELECT Name,Status FROM table1 WHERE id=" + item_id.Value.ToString
rs.Open(SQL, dbConn)
While Not rs.EOF
txtName.Text = rs.Fields.Item("Name").Value
ddlstatus.SelectedIndex = 1
rs.MoveNext()
End While
rs.Close()
rs = Nothing
dbConn.Close()
dbConn = Nothing
Can I replace recordset with SQLDataReader and if I can can you please show me the changes in code?
Its highly recommend that you use the using pattern:
Dim sConnection As String = "server=(local);uid=sa;pwd=PassWord;database=DatabaseName"
Using Con As New SqlConnection(sConnection)
Con.Open()
Using Com As New SqlCommand("Select * From tablename", Con)
Using RDR = Com.ExecuteReader()
If RDR.HasRows Then
Do While RDR.Read
txtName.Text = RDR.Item("Name").ToString()
Loop
End If
End Using
End Using
Con.Close()
End Using
You will have to swap out a few things, something similar to the following.
Here is an example, you will need to modify this to meet your goal, but this shows the difference.
I also recommend using a "Using" statement to manage the connection/reader. Also, a parameterized query.
Dim sConnection As String = "server=(local);uid=sa;pwd=PassWord;database=DatabaseName"
Dim objCommand As New SqlCommand
objCommand.CommandText = "Select * From tablename"
objCommand.Connection = New SqlConnection(sConnection)
objCommand.Connection.Open()
Dim objDataReader As SqlDataReader = objCommand.ExecuteReader()
If objDataReader.HasRows Then
Do While objDataReader.Read()
Console.WriteLine(" Your name is: " & Convert.ToString(objDataReader(0)))
Loop
Else
Console.WriteLine("No rows returned.")
End If
objDataReader.Close()
objCommand.Dispose()
Dim rdrDataReader As SqlClient.SqlDataReader
Dim cmdCommand As SqlClient.SqlCommand
Dim dtsData As New DataSet
Dim dtbTable As New DataTable
Dim i As Integer
Dim SQLStatement as String
msqlConnection.Open()
cmdCommand = New SqlClient.SqlCommand(SQLStatement, msqlConnection)
rdrDataReader = cmdCommand.ExecuteReader()
For i = 0 To (rdrDataReader.FieldCount - 1)
dtbTable.Columns.Add(rdrDataReader.GetName(i), rdrDataReader.GetFieldType(i))
Next
dtbTable.BeginLoadData()
Dim values(rdrDataReader.FieldCount - 1) As Object
While rdrDataReader.Read
rdrDataReader.GetValues(values)
dtbTable.LoadDataRow(values, True)
End While
dtbTable.EndLoadData()
dtsData.Tables.Add(dtbTable)
msqlConnection.Close()
Return dtsData