How to refresh a dataGridView - vb.net

I have a problem refreshing a DataGridView control after Insert or Update. The source code:
Get all rows from table in datatable and set to the datasource:
Dim dt1 as DataTable = GetData("SELECT * FROM CLAIMSTATE ")
dataGrid.DataSource = dt1
Update Event if ID is valued, and Insert if it isn't:
Private Sub dataGrid_RowLeave(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles dataGrid.RowLeave
Dim row As DataGridViewRow = CType(sender, DataGridView).Rows(e.RowIndex)
Dim query As New StringBuilder("")
If row.Cells(0).Value & "" = "" Then
query.Append("INSERT INTO CLAIMSTATE ")
query.Append("(CST_CODE, CST_LABEL, CST_POINTS)")
query.Append("VALUES ")
query.Append("(?, ?, ?)")
Else
query.Append("Update CLAIMSTATE ")
query.Append("SET CST_CODE = ?, ")
query.Append("CST_LABEL = ?, ")
query.Append("CST_POINTS = ? ")
query.Append("WHERE CST_ID = ? ")
End If
Dim command As New OdbcCommand(query.ToString(), con)
command.Parameters.Add("#cst_code", OdbcType.Char).Value = row.Cells(1).Value
command.Parameters.Add("#cst_label", OdbcType.NVarChar).Value = row.Cells(2).Value
command.Parameters.Add("#cst_points", OdbcType.Decimal).Value = row.Cells(3).Value
command.Parameters.Add("#cst_id", OdbcType.BigInt).Value = row.Cells(0).Value
Dim res As Integer = ExecuteNonQuery(command)
End Sub
Public Function GetData(ByRef sqlQuery As String) As DataTable
Dim command As New OdbcCommand(sqlQuery, con)
Try
If con.State = ConnectionState.Closed Then
con.ConnectionString = conString
con.Open()
End If
Using dr As OdbcDataReader = command.ExecuteReader()
Dim dt As New DataTable()
dt.Load(dr)
Return dt
End Using
'con.Close()
Catch ex As Exception
MsgBox(ex.Message)
con.Close()
Return Null
End Try
End Function
Public Function ExecuteNonQuery(ByRef command As OdbcCommand) As Integer
Dim result As Integer = 0
If con.State = ConnectionState.Closed Then
con.ConnectionString = conString
con.Open()
End If
'Dim command As New OdbcCommand(sqlQuery, conn)
Try
'command.Connection = con
'Dim cmd As New OdbcCommand( sqlQuery, conn)
result = command.ExecuteNonQuery()
Catch
result = 0
If con IsNot Nothing Then
con.Close()
command.Dispose()
End If
Finally
command.Dispose()
End Try
Return result
End Function
I tried to get all records from the table and set the datasource again at the end of the method but it doesn't work.
If I put the code:
dataGrid.Rows.Clear()
dataGrid.Columns.Clear()
dt1 = GetData("SELECT * FROM CLAIMSTATE ")
dataGrid.DataSource = dt1
on end of event method RowLeave I recive this error:
"Operation is not valid because it results in a reentrant call to the
SetCurrentCellAddressCore function"
on dataGrid.Rows.Clear(), but if I remove the line codes Rows.Clear() and Columns.Clear(), the debug cursor after execute dataGrid.DataSource = dt1 return to begin of event method an execute some code again and after I recive the some error "...reentrant call to the SetCurrentCellAddressCore function"!
Help me, please!

Here is a C# class I have that I use to connect search my GridView. What you need should be similar I would think.
protected void lbSearch_Click(object sender, EventArgs e)
{
if (txtSearch.Text.Trim().Length > 0)
{
odsInbox.FilterExpression =
string.Format("(l_name LIKE '*{0}*') OR (f_name LIKE '*{0}*') OR (title LIKE '*{0}*')",
txtSearch.Text);
}
else
{
odsInbox.FilterExpression = string.Empty;
}
gvInbox.DataBind();
}
protected void lbClear_Click(object sender, EventArgs e)
{
odsInbox.FilterExpression = string.Empty;
txtSearch.Text = "";
gvInbox.DataBind();
}
I hope this gets you on the right track.

For solving this problem I use OdbcDataAdapter. I save all changes with adapter.Update(dataTable) and after I fill the datatable again: adapter.fill(dataTable).

Related

Database locked in vb.net when trying to update data in vb.net

Hello I have a simple method to update customer details in one of my database tables however when i try to update it an error occurs saying the database is locked. I have no idea how to fix this because my add and delete queries work just fine.
This is the error message:
System.Data.SQLite.SQLiteException: 'database is locked
database is locked'
Public Sub updateguest(ByVal sql As String)
Try
con.Open()
With cmd
.CommandText = sql
.Connection = con
End With
result = cmd.ExecuteNonQuery
If result > 0 Then
MsgBox("NEW RECORD HAS BEEN UPDATED!")
con.Close()
Else
MsgBox("NO RECORD HASS BEEN UPDATDD!")
End If
Catch ex As Exception
MsgBox(ex.Message)
Finally
con.Close()
End Try
End Sub
Private Sub IbtnUpdate_Click(sender As Object, e As EventArgs) Handles ibtnUpdate.Click
Dim usql As String = "UPDATE Customers SET fname = '" & txtFName.Text & "'" & "WHERE CustomerID ='" & txtSearchID.Text & "'"
updateguest(usql)
End Sub
Private Sub IbtnSearch_Click(sender As Object, e As EventArgs) Handles ibtnSearch.Click
Dim sSQL As String
Dim newds As New DataSet
Dim newdt As New DataTable
Dim msql, msql1 As String
Dim con As New SQLiteConnection(ConnectionString)
con.Open()
msql = "SELECT * FROM Customers Where Fname Like '" & txtSearchName.Text & "%'"
msql1 = "SELECT * FROM Customers Where CustomerID '" & txtSearchID.Text & "'"
Dim cmd As New SQLiteCommand(msql, con)
Dim cmd1 As New SQLiteCommand(msql1, con)
Dim dt = GetSearchResults(txtSearchName.Text)
dgvCustomerInfo.DataSource = dt
Dim mdr As SQLiteDataReader = cmd.ExecuteReader()
If mdr.Read() Then
If txtSearchName.Text <> "" Then
sSQL = "SELECT * FROM customers WHERE fname LIKE'" & txtSearchName.Text & "%'"
Dim con1 As New SQLiteConnection(ConnectionString)
Dim cmd2 As New SQLiteCommand(sSQL, con1)
con1.Open()
Dim da As New SQLiteDataAdapter(cmd2)
da.Fill(newds, "customers")
newdt = newds.Tables(0)
If newdt.Rows.Count > 0 Then
ToTextbox(newdt)
End If
dgvCustomerInfo.DataSource = newdt
con1.Close()
txtSearchID.Clear()
ElseIf txtSearchID.Text <> "" Then
sSQL = "SELECT * FROM customers WHERE CustomerID ='" & txtSearchID.Text & "'"
Dim con2 As New SQLiteConnection(ConnectionString)
Dim cmd2 As New SQLiteCommand(sSQL, con2)
con2.Open()
Dim da As New SQLiteDataAdapter(cmd2)
da.Fill(newds, "customers")
newdt = newds.Tables(0)
If newdt.Rows.Count > 0 Then
ToTextbox(newdt)
End If
dgvCustomerInfo.DataSource = newdt
con2.Close()
txtSearchName.Clear()
End If
Else
MsgBox("No data found")
End If
End Sub
Private Sub IbtnDelete_Click(sender As Object, e As EventArgs) Handles ibtnDelete.Click
Dim dsql As String = "DELETE FROM customers WHERE customerid = " & txtSearchID.Text & ""
deleteme(dsql)
updatedgv(dgvCustomerInfo)
txtSearchID.Clear()
txtSearchName.Clear()
End Sub
Public Sub deleteme(ByVal sql As String)
Try
con.Open()
With cmd
.CommandText = sql
.Connection = con
End With
result = cmd.ExecuteNonQuery
If result > 0 Then
MsgBox("NEW RECORD HAS BEEN DELTED!")
con.Close()
Else
MsgBox("NO RECORD HASS BEEN DELTED!")
End If
Catch ex As Exception
MsgBox(ex.Message)
Finally
con.Close()
End Try
End Sub
You made a good start on keeping your database code separate from you user interface code. However, any message boxes should be shown in the user interface and any sql statements should be written in the data access code.
I used Using...End Using blocks to ensure that database objects are closed and disposed. I used parameters to protect against sql injection. I am not too sure of the mapping of DbType types to Sqlite types. You might have to fool with that a bit. In you original Update statement you had the ID value in quotes. This would pass a string. When you use parameters, you don't have to worry about that or ampersands and double quotes. Just one clean string.
Private ConStr As String = "Your connection string"
Public Function updateguest(FirstName As String, ID As Integer) As Integer
Dim Result As Integer
Dim usql As String = "UPDATE Customers SET fname = #fname WHERE CustomerID = #ID;"
Using con As New SQLiteConnection(ConStr),
cmd As New SQLiteCommand(usql, con)
cmd.Parameters.Add("#fname", DbType.String).Value = FirstName
cmd.Parameters.Add("#ID", DbType.Int32).Value = ID
con.Open()
Result = cmd.ExecuteNonQuery
End Using
Return Result
End Function
Private Sub IbtnUpdate_Click(sender As Object, e As EventArgs) Handles ibtnUpdate.Click
Try
Dim Result = updateguest(txtFName.Text, CInt(txtSearchID.Text))
If Result > 0 Then
MsgBox("New RECORD HAS BEEN UPDATED!")
Else
MsgBox("NO RECORD HAS BEEN UPDATDD!")
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub

Access database too slow populating DatagridView

I have an app with several datagridviews, and now, with more than 260 rows, my datagrid is too slow filling up, I don't know how I can lower the time.
Here is my codes:
Public cs As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & Application.StartupPath & "\BD_Estaleiro.accdb"
Public con As New OleDbConnection(cs)
Public cmd As OleDbCommand
Public dr As OleDbDataReader
Public query As String
Reader Function:
Public Function executar_query_Reader(ByVal Instrucao As String) As OleDb.OleDbDataReader
Dim datareader As OleDbDataReader = Nothing
cmd = New OleDbCommand(Instrucao, con)
Try
If con.State = ConnectionState.Open Then
con.Close()
End If
con.Open()
datareader = cmd.ExecuteReader
Catch ex As Exception
MessageBox.Show(ex.Message) 'mensagem de erro, se aplicavel
Finally
End Try
Return datareader 'retornar os dados atraves da variavel datareader
End Function
Populating the Datagrid:
Public Sub carregar_saidas(ByVal DG As DataGridView)
n_rows = 0
DG.Rows.Clear()
query = "Select * from tbl_saidas as s, tbl_produtos as p Where s.Produto=p.Produto Order By s.Data DESC"
dr = executar_query_Reader(query)
While dr.Read
n_rows += 1
Dim n As Integer = DG.Rows.Add()
DG.Rows.Item(n).Cells(0).Value = dr("ID")
DG.Rows.Item(n).Cells(1).Value = dr("s.Produto")
DG.Rows.Item(n).Cells(2).Value = dr("s.Quantidade")
DG.Rows.Item(n).Cells(3).Value = dr("Unidade")
DG.Rows.Item(n).Cells(4).Value = dr("Obra")
DG.Rows.Item(n).Cells(5).Value = Format(dr("Data"), "dd/MM/yyyy")
DG.Rows.Item(n).Cells(6).Value = Format$(CSng(dr("Valor_uni")), "###,####,##0.00") & " €"
DG.Rows.Item(n).Cells(7).Value = Format$(CSng(dr("Total")), "###,####,##0.00") & " €"
End While
con.Close()
End Sub
Thanks for any help
Rather than adding individual Rows and Columns, you want to bind to the grid:
Public Sub carregar_saidas(ByVal DG As DataGridView)
Dim query As String = "Select * from tbl_saidas as s, tbl_produtos as p Where s.Produto=p.Produto Order By s.Data DESC"
Dim dr As OleDbDataReader = executar_query_Reader(query)
DG.DataSource = dr
End Sub
You'll need to have defined the columns on DataGridView to map the fields in the data reader.
You should also look into modifying the executar_query_Reader() method to support parameterized queries.

Am new to asp.net and vb.net.,now am trying to make a gridview of a database table

now am trying to make a gridview of a database table named UploadProject.while selecting row of gridview display image in seperate image field by using imageurl At the time of compiling of following code image not displayed.an error occured..."incorect syntax near '='".Any body please help me to solve this problem
Protected Sub OnSelectedIndexChanged(sender As Object, e As System.EventArgs) Handles GridView1.SelectedIndexChanged
Dim row As GridViewRow = GridView1.SelectedRow
lblimageid.Text = row.Cells(0).Text
lbltitle.Text = row.Cells(1).Text
get_Address()
get_Image()
End Sub
Public Sub get_Address()
Dim qry As String
Try
cn.Open()
qry = "select (title,imageurl) from [UploadProject] where [id] = '" & lblimageid.Text & "'"
cmnd = New SqlCommand(qry, cn)
sdr = cmnd.ExecuteReader
While (sdr.Read())
lbltitle.Text = sdr.GetValue(0).ToString
Image2.ImageUrl = sdr.GetValue(1).ToString
End While
cn.Close()
Catch ex As Exception
lblmes2.ForeColor = Drawing.Color.Red
lblmes2.Text = ex.Message
Finally
cn.Close()
End Try
End Sub
Public Sub get_Image()
Dim qry As String
Try
cn.Open()
qry = "select title,imageurl from UploadProject where id = " & lblimageid.Text
cmnd = New SqlCommand(qry, cn)
sdr = cmnd.ExecuteReader
While (sdr.Read())
lbltitle.Text = sdr.GetValue(0).ToString
Image2.ImageUrl = sdr.GetValue(1).ToString
End While
cn.Close()
Catch ex As Exception
lblmes1.ForeColor = Drawing.Color.Red
lblmes1.Text = ex.Message
Finally
cn.Close()
End Try
End Sub
Public Sub getProjectDT()
Dim qry As String
Try
qry = "select id,title,date from UploadProject "
sda = New SqlDataAdapter(qry, cn)
ds = New DataSet
sda.Fill(ds, "UploadProject")
GridView1.DataSource = ds.Tables(0)
GridView1.DataBind()
Catch ex As Exception
Finally
cn.Close()
End Try
End Sub

update query dont work in vb.net

i want write update statement in code behind in vb.net.if ICCID is exists in tbl_ICCID then change status from 0 to 1 and Pic_Correct_ICCID.visible=true, if not exists , display "Not found".
i wrote this code but doesnt work and for all of ICCID that not exists in Tbl_ICCID Pic_Correct_ICCID.visible=true.
Please check my code and solve my problem.
in Cls_ICCID:
Public Function Update_Status(ByVal ICCID_No As String, ByVal status As Integer) As String
Try
Dim cmd As SqlCommand
Dim sql As String
Dim sql2 As String
Dim myConnection As SqlConnection = New SqlConnection()
myConnection.ConnectionString = "Data Source=TEHRANI\TEHRANI;Initial Catalog=GSMProduction;Persist Security Info=True;User ID=sa;Password=1"
**sql = "UPDATE Tbl_ICCID SET Status='" & status & "' Where ( ICCID = '" & ICCID_No & "' )"**
myConnection.Open()
cmd = New SqlCommand(sql, myConnection)
cmd.ExecuteNonQuery()
cmd.Dispose()
myConnection.Close()
Update_Status = ""
Catch ex As SqlException
Update_Status = "Not found"
Catch ex As Exception
Update_Status = "Not connect to server"
End Try
End Function
in Frm_Packing
Private Sub Txt_ICCID_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Txt_ICCID.TextChanged
Pic_BP_Correct.Visible = False
Pic_BP_Wrong.Visible = False
Try
If Txt_ICCID.Text.Length = Txt_ICCID.MaxLength Then
lblError.Text = clsICCID.Update_Status(Txt_ICCID.Text.ToString(), 1)
lblError.ForeColor = Color.Red
stream = New System.IO.MemoryStream
pic_barcode = Nothing
cls.btnEncode(pic_barcode, Txt_ICCID.Text.Trim)
pic_barcode.Save(stream, System.Drawing.Imaging.ImageFormat.Png)
f = New IO.FileStream("C:\test55.png", IO.FileMode.Create, IO.FileAccess.ReadWrite)
b = stream.ToArray
f.Write(b, 0, b.Length)
f.Close()
Dim Val() = {stream.ToArray, Txt_ICCID.Text.Trim}
ds.Tables(0).Rows.Add(Val)
crp_report.SetDataSource(ds.Tables(0))
frm_crp.CrystalReportViewer1.ReportSource = crp_report
If lblError.Text = "" Then
Pic_BP_Correct.Visible = True
GBDoubleCheck.Visible = True
Txt_LabelBarcode.Focus()
Else
Pic_BP_Wrong.Visible = True
End If
End If
Catch ex As Exception
Pic_BP_Wrong.Visible = True
End Try
End Sub
Most probably due to sending status column value as string instead of int. You should remove those single-quotes. Also, this is really really bad practice to concat queries like that. Use CommandBuilders kind of thing or Typed DataSets for saving yourself against SQL injections.

error :ExecuteNonQuery: CommandText property has not been initialized

this code is in the button click , i get each data out using spilt
but i encounter error at "cmd.CommandType = CommandType.Text"
Dim conn As New SqlConnection(GetConnectionString())
Dim sb As New StringBuilder(String.Empty)
Dim splitItems As String() = Nothing
For Each item As String In sc
Const sqlStatement As String = "INSERT INTO Date (dateID,date) VALUES"
If item.Contains(",") Then
splitItems = item.Split(",".ToCharArray())
sb.AppendFormat("{0}('{1}'); ", sqlStatement, splitItems(0))
End If
Next
Try
conn.Open()
Dim cmd As New SqlCommand(sb.ToString(), conn)
cmd.CommandType = CommandType.Text
cmd.ExecuteNonQuery()
Page.ClientScript.RegisterClientScriptBlock(GetType(Page), "Script", "alert('Records Successfuly Saved!');", True)
Catch ex As System.Data.SqlClient.SqlException
Dim msg As String = "Insert Error:"
msg += ex.Message
Throw New Exception(msg)
Finally
conn.Close()
End Try
the same code , the below work
Dim conn As New SqlConnection(GetConnectionString())
Dim sb As New StringBuilder(String.Empty)
Dim splitItems As String() = Nothing
For Each item As String In sc
Const sqlStatement As String = "INSERT INTO GuestList (groupID,guest,contact,eEmail,relationship,info,customerID) VALUES"
If item.Contains(",") Then
splitItems = item.Split(",".ToCharArray())
sb.AppendFormat("{0}('{1}','{2}','{3}','{4}','{5}','{6}','{7}'); ", sqlStatement, splitItems(0), splitItems(1), splitItems(2), splitItems(3), splitItems(4), splitItems(5), Session("customerID"))
End If
Next
Try
conn.Open()
Dim cmd As New SqlCommand(sb.ToString(), conn)
cmd.CommandType = CommandType.Text
cmd.ExecuteNonQuery()
Page.ClientScript.RegisterClientScriptBlock(GetType(Page), "Script", "alert('Records Successfuly Saved!');", True)
Catch ex As System.Data.SqlClient.SqlException
Dim msg As String = "Insert Error:"
msg += ex.Message
Throw New Exception(msg)
Finally
conn.Close()
End Try
You never set the CommandText property.
You don't need to set CommandType at all.
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles
MyBase.Load
dim dt as new datatable
constr.Open()
cmd = New OleDbCommand("SELECT * FROM tblGender )
da = New OleDbDataAdapter(cmd)
da.Fill(dt)
constr.Close()
With ComboBox1
.DataSource = dt
.DisplayMember = "Gender"
End With
dim dt1 as new datatable
constr.Open()
cmd = New OleDbCommand("SELECT * FROM tblStatus )
da = New OleDbDataAdapter(cmd)
da.Fill(dt)
constr.Close()
With ComboBox2
.DataSource = dt1
.DisplayMember = "Status"
End With
dim dt2 as new datatable
constr.Open()
cmd = New OleDbCommand("SELECT * FROM tblDepartment )
da = New OleDbDataAdapter(cmd)
da.Fill(dt)
constr.Close()
With ComboBox3
.DataSource = dt2
.DisplayMember = "Department"
End With
End Sub
See this
Dim conn As New SqlConnection(GetConnectionString())
Dim sb As New StringBuilder(String.Empty)
Dim splitItems As String() = Nothing
For Each item As String In sc
'Const sqlStatement As String = "INSERT INTO Date (dateID,date) VALUES"
'If item.Contains(",") Then
' splitItems = item.Split(",".ToCharArray())
' sb.AppendFormat("{0}('{1}'); ", sqlStatement, splitItems(0))
'End If
Const sqlStatement As String = "INSERT INTO Date (dateID,date) VALUES"
If item.Contains(",") Then
splitItems = item.Split(",".ToCharArray())
sb.AppendFormat("{0}({1},'{2}'); ", sqlStatement, splitItems(0), splitItems(1))
End If
Next
Try
conn.Open()
Dim cmd As New SqlCommand(sb.ToString(), conn)
cmd.CommandType = CommandType.Text
cmd.ExecuteNonQuery()
Page.ClientScript.RegisterClientScriptBlock(GetType(Page), "Script", "alert('Records Successfuly Saved!');", True)
Catch ex As System.Data.SqlClient.SqlException
Dim msg As String = "Insert Error:"
msg += ex.Message
Throw New Exception(msg)
Finally
conn.Close()
End Try