while filling data grid view using sql reader application getting slow - vb.net

I have a windows form...i am trying to fill my data grid view using sql datareader,,
while clicking button i try to fill my data grid view..
i wrote one function for filling grid view..
Sub filldgv()
DGVReleased.Rows.Clear()
Dim carid As String
Dim VehicleNo As String
Dim DriverID As String
Dim krrt As Integer
Dim Dt As Integer
Dim cmd As New SqlCommand("IBS_fetchresleaseVehicle", con.connect)
cmd.CommandType = CommandType.StoredProcedure
cmd.Parameters.Add("#locid", SqlDbType.Int).Value = Glocid
dr = cmd.ExecuteReader
While dr.Read
If dr("TBarcode") Is DBNull.Value Then
carid = ""
Else
carid = dr("TBarcode")
End If
If dr("PlateNo") Is DBNull.Value Then
VehicleNo = ""
Else
VehicleNo = dr("PlateNo")
End If
If dr("DelEcode") Is DBNull.Value Then
DriverID = ""
Else
DriverID = dr("DelEcode")
End If
If dr("KRRT") Is DBNull.Value Then
Else
krrt = dr("KRRT")
End If
If dr("DT") Is DBNull.Value Then
Else
Dt = dr("DT")
End If
Dim row0 As String() = {carid, VehicleNo, DriverID, krrt, Dt}
DGVReleased.Rows.Insert(0, row0)
End While
dr.Close()
con.disconnect()
End Sub
then i am calling this function in my button click event.here first am removing all records from grid view then i am filling..while coming more records to data grid view my system is getting hang..is there any way to do this very simple manner..any help is very appreciable..

use DataGridView.Rows.AddRange. Collect data in List(Of DataGridViewRow), then only after the loop add them to the DataGridView:
Sub filldgv()
Dim ListRows As New List(Of DataGridViewRow)()
Dim cmd = New SqlCommand("IBS_fetchresleaseVehicle")
cmd.CommandType = CommandType.StoredProcedure
cmd.Connection = con.connect
cmd.Parameters.Add("#locid", SqlDbType.Int).Value = Glocid
Dim dr = cmd.ExecuteReader
Dim ListRows As New List(Of DataGridViewRow)()
While dr.Read
Dim DgvRow = New DataGridViewRow
Dim o = {dr("TBarcode").ToString(),
dr("PlateNo").ToString(),
dr("DelEcode").ToString(),
If(IsDBNull(dr("KRRT")), 0, dr("KRRT")),
If(IsDBNull(dr("DT")), 0, dr("DT")) }
DgvRow.CreateCells(o)
ListRows.Add(DgvRow)
End While
dr.Close()
con.disconnect()
Dim SavedBool = DGVReleased.AllowUserToAddRows
DGVReleased.AllowUserToAddRows = False
DGVReleased.Rows.AddRange(ListRows.ToArray())
DGVReleased.AllowUserToAddRows = SavedBool
End Sub
Use DataTable & DataBinding, then populate DataTable in Background-Thread:
Sub filldgv()
Dim dt As New DataTable
dt.Columns.Add("", GetType(String))
dt.Columns.Add("", GetType(String))
dt.Columns.Add("", GetType(String))
dt.Columns.Add("", GetType(Integer))
dt.Columns.Add("", GetType(Integer))
DGVReleased.DataSource = dt
Task.Factory.StartNew(Sub() Populate(dt))
''you can replace last line with this:
'Dim bgw = New BackgroundWorker()
'AddHandler bgw.DoWork, Sub() Populate(dt)
'bgw.RunWorkerAsync()
End Sub
Sub Populate(dt As DataTable)
Dim cmd = New SqlCommand("IBS_fetchresleaseVehicle")
cmd.CommandType = CommandType.StoredProcedure
cmd.Connection = con.connect
cmd.Parameters.Add("#locid", SqlDbType.Int).Value = Glocid
Dim dr = cmd.ExecuteReader
While dr.Read
Dim o = {dr("TBarcode").ToString(),
dr("PlateNo").ToString(),
dr("DelEcode").ToString(),
If(IsDBNull(dr("KRRT")), 0, dr("KRRT")),
If(IsDBNull(dr("DT")), 0, dr("DT")) }
dt.Rows.Add(o)
End While
dr.Close()
con.disconnect()
End Sub
Tip:
instead the if conditions, you can use shortly If Operator:
So instead:
If IsDBNull(dr("TBarcode") Then
carid = 0
Else
carid = dr("TBarcode")
End If
Written:
carid = If(IsDBNull(dr("TBarcode")), 0, dr("TBarcode"))
Thanks to #SSS: For String Fields you can simply:
carid = dr("TBarcode").ToString()

Related

how to put numbering for Images in Listview

How to add numbering Images in Listview and below attached the code.
Private Sub retrieve()
ListView1.Clear()
Dim imglist As New ImageList
imglist.ColorDepth = ColorDepth.Depth32Bit
ListView1.LargeImageList = imglist
ListView1.LargeImageList.ImageSize = New System.Drawing.Size(200, 200)
Dim strsql As String = "select * from picEmploy where NumFile=" & TextBox1.Text
Dim dt_images As New DataTable
cmd.Connection = con
cmd.CommandText = strsql
adp.SelectCommand = cmd
adp.Fill(ds)
For Each dr As DataRow In ds.Tables(0).Rows
Dim imb_buffer = CType(dr("pic"), Byte())
Dim img_stream As New IO.MemoryStream(imb_buffer, True)
img_stream.Write(imb_buffer, 0, imb_buffer.Length)
imglist.Images.Add(dr("NumFile").ToString(), New Bitmap(img_stream))
img_stream.Close()
Dim lsvparent As New ListViewItem
'lsvparent.Text = dr("pic").ToString
lsvparent.ImageKey = dr("NumFile").ToString
ListView1.Items.Add(lsvparent)
Next
End Sub

how to add list in `DATAGRIDVIEW` with combobox on runtime

i tried the following code but it adds the list every time when we start new row so if we have two rows its add it two times if we move to three rows it adds the list for three time
Please provide me simple and easy way to add the list into the combobox of datagridview
Dim CON As New MySqlConnection("server=localhost; username=root; password=Masoom1; database=airtech_db;")
Dim cmd As New MySqlCommand("Select * from `Suppliers`;", CON)
Dim da As New MySqlDataAdapter("Select * from `Suppliers`;", CON)
Dim ds As New DataSet
Dim dr As MySqlDataReader
Dim TOTAL_SUPPLIERS As Integer
CON.Open()
da.Fill(ds)
dr = cmd.ExecuteReader
TOTAL_SUPPLIERS = ds.Tables(0).Rows.Count
Dim TOTAL_SUPPLIERS_ARRAY(TOTAL_SUPPLIERS) As String, ARRAYINDEX As Integer
ARRAYINDEX = 0
Do While dr.Read() = True
TOTAL_SUPPLIERS_ARRAY(ARRAYINDEX) = dr("Supplier_Name").ToString()
ARRAYINDEX += 1
Loop
CON.Close()
Dim cbCell As New DataGridViewComboBoxCell
For k = 0 To DataGridView1.Rows.Count - 1
cbCell = DataGridView1.Rows(k).Cells("Supplier_Name")
For iIndex = 0 To UBound(TOTAL_SUPPLIERS_ARRAY) - 1
cbCell.Items.Add(TOTAL_SUPPLIERS_ARRAY(iIndex))
Next
Next
You can set it only once for a column.
For example you can populate combobox when loading a form.
Private Sub Form_Load(sender As Object, e As EventArgs) Handles MyForm.Load
With Me.DataGridView.Columns("Supplier_Name")
.DataSource = GetSupplierNames()
End With
End Sub
Private Function GetSupplierNames() As List(Of String)
Dim query As String = "SELECT Supplier_Name FROM Suppliers"
Using connection As New MySqlConnection(connectionString)
Using command As New MySqlCommand(query, connection)
connection.Open()
Dim supplierNames = new List(Of String)()
Using reader AS MySqlDataReader = command.ExecuteReader()
While reader.Read()
Dim name As String = reader.GetString(0)
supplierNames.Add(name)
End While
End Using
Return supplierNames
End Using
End Using
End Function
well I found a simple solution to existing code to fix the problem as every time it runs clear the existing list and let the list add again so add cbCell.Items.Clear()to code helped
Dim cbCell As New DataGridViewComboBoxCell
For k = 0 To DataGridView1.Rows.Count - 1
cbCell = DataGridView1.Rows(k).Cells("Supplier_Name")
cbCell.Items.Clear()
For iIndex = 0 To UBound(TOTAL_SUPPLIERS_ARRAY)
cbCell.Items.Add(TOTAL_SUPPLIERS_ARRAY(iIndex))
Next
Next

Delete Row / Remove Row

I want to delete my rows in gridview, but when I try many code the error are same.
When I try this
Using sqlCon As New SqlConnection(PyrDLL.Koneksi.ConnectionString)
Using cmd As New SqlCommand()
cmd.CommandText = "xyz"
cmd.Connection = sqlCon
sqlCon.Open()
Dim da As New SqlDataAdapter(cmd)
Dim dt As New DataTable()
da.Fill(dt)
Gridview1.DataSource = dt
Gridview1.DataBind()
sqlCon.Close()
If Gridview1.Rows.Count = 0 Then
Dim dtempty As DataTable = Nothing
dtempty = (DirectCast(Gridview1.DataSource, DataTable)).Clone()
dtempty.Rows.Add(dtempty.NewRow())
Gridview1.DataSource = dtempty
Gridview1.DataBind()
Gridview1.Rows(0).Visible = False
'Gridview1.Rows(0).Controls.Clear()
Else
For i As Integer = 0 To dt.Rows.Count - 1
dt.Rows(i)("rupiah") = PyrDLL.Decrypt(dt.Rows(i)("rupiah"))
dt.Rows(i)("rupiah") = Decimal.Parse(dt.Rows(i)("rupiah")).ToString()
'i = i + 1
Next
Gridview1.DataBind()
For i As Integer = Gridview1.Rows.Count - 1 To 1 Step -1
Dim row As GridViewRow = Gridview1.Rows(i)
Dim prevrow As GridViewRow = Gridview1.Rows(i - 1)
If (TryCast(Gridview1.Rows(i).Cells(1).FindControl("lblketerangan"), Label).Text.ToString() = TryCast(Gridview1.Rows(i - 1).Cells(1).FindControl("lblketerangan"), Label).Text.ToString()) And (TryCast(Gridview1.Rows(i).Cells(0).FindControl("lblcomp"), Label).Text.ToString() = TryCast(Gridview1.Rows(i - 1).Cells(0).FindControl("lblcomp"), Label).Text.ToString()) Then
Dim total As Integer = Convert.ToDecimal(TryCast(Gridview1.Rows(i - 1).Cells(2).FindControl("lblrupiah"), Label).Text)
Dim total2 As Integer = Convert.ToDecimal(TryCast(Gridview1.Rows(i).Cells(2).FindControl("lblrupiah"), Label).Text)
Dim total3 As Decimal
total3 = total + total2
DirectCast(Gridview1.Rows(i - 1).Cells(2).FindControl("lblrupiah"), Label).Text = Decimal.Parse(total3).ToString()
row.Visible = False
'Gridview1.Rows.Remove(Gridview1.Rows(i)) <--- if i comment here its run without problem
End If
Next
End If
End Using
End Using
the error
Remove' is not a member of 'System.Web.UI.WebControls.GridViewRowCollection'
Can you help me?
now, i hide the row after i sum it but i want to auto delete / remove row after i sum it not only hide
Thanks
I am not sure what you are trying to do when there are no rows, the gridview would be empty
You should do the following instead:
'Call GetData() every time you want to bind data to the gridview
Private Function GetData()
Gridview1.DataSource = Nothing
Gridview1.DataBind()
Dim strQuery = "SELECT..."
Dim dt As New DataTable()
Using sqlCon As New SqlConnection(PyrDLL.Koneksi.ConnectionString)
Using cmd As New SqlCommand(strQuery, sqlCon)
'Add cmd parameters as required to prevent SqlInjection
sqlCon.Open()
Using ada As New SqlDataAdapter(cmd)
ada.Fill(dt)
Gridview1.DataSource = dt
Gridview1.DataBind()
End Using
End Using
End Using
End Function
When handling the data in the gridview you can use RowDataBound, you could then call a separate function to handle deleting a row after your logic is handled where the criteria is met to delete a row
Protected Sub Gridview1_RowDataBound(sender As Object, e As GridViewRowEventArgs) Handles Gridview1.RowDataBound
If e.Row.RowType = DataControlRowType.DataRow Then
'Handle databound logic
End If
End Sub
You should be able to tailor this to your needs, just called GetData() everytime you need to rebind data to the gridview
I solved my problem
i cant remove rows from data gridview but i remove data from data table and bind it after thats
thanks everyone

DataGridView ScrollBar bug

When I get data for the DataGridView, my form freezes until the While loop completes, but then my scrollbar worked fine. I tried calling Application.DoEvents(); but that didn't work either.
If I get the data in a thread, then my form does not freeze, but the scrollbar disables and does not work after the While completes. I tried a BackgroundWorker but the scrollbar has a problem when using that too.
Private Sub dg()
myth = New Threading.Thread(AddressOf dgd)
myth.IsBackground = True
myth.Start()
End Sub
Private Sub dgd()
Dim x As Integer
If DataGridView1.Rows.Count = 0 Then x = 0 Else x = DataGridView1.Rows.Count
Try
Dim conn35a As New OleDbConnection("connstring")
Dim cmd35a As New OleDbCommand
cmd35a.CommandText = "Select count(*) from asd where downur Is Null"
cmd35a.CommandType = CommandType.Text
cmd35a.Connection = conn35a
conn35a.Open()
Dim returnValueaa As Integer = cmd35a.ExecuteScalar()
conn35a.Close()
Dim komut As String = "Select * from asd where downur Is Null"
Dim conn2 As New OleDbConnection("connstring")
conn2.Open()
Dim cmd2 As New OleDbCommand(komut, conn2)
Dim dr2 As OleDbDataReader = cmd2.ExecuteReader
If dr2.HasRows Then
While dr2.Read
Dim conn35 As New OleDbConnection("connstring")
Dim cmd35 As New OleDbCommand
cmd35.CommandText = "select count(*) from grid where ur = '" + dr2.Item("ur").ToString + "'"
cmd35.CommandType = CommandType.Text
cmd35.Connection = conn35
conn35.Open()
Dim returnValuea = cmd35.ExecuteScalar()
conn35.Close()
If returnValuea = 0 Then
DataGridView1.Rows.Add()
DataGridView1.Rows.Item(x).Cells(0).Value = x + 1
DataGridView1.Rows.Item(x).Cells(4).Value = "ID"
DataGridView1.Rows.Item(x).Cells(5).Value = dr2.Item("ur").ToString
DataGridView1.Rows.Item(x).Cells(6).Value = dr2.Item("ch").ToString
DataGridView1.Rows.Item(x).Cells(7).Value = dr2.Item("ti").ToString
DataGridView1.Rows.Item(x).Cells(8).Value = ".."
Dim client2 As New WebClient
Dim url As String = dr2.Item("pic").ToString
DataGridView1.Rows.Item(x).Cells(12).Value = New Bitmap(New MemoryStream(client2.DownloadData(url)))
DataGridView1.Rows.Item(x).Cells(13).Value = dr2.Item("vi")
DataGridView1.Rows.Item(x).Cells(14).Value = dr2.Item("su").ToString()
Dim con4 As New OleDbConnection("connstring")
con4.Open()
Dim cmd5 = New OleDbCommand("INSERT INTO grid (ur) VALUES (#ur)", con4)
cmd5.CommandType = CommandType.Text
cmd5.Parameters.Add("#ur", OleDbType.VarChar, 500).Value = dr2.Item("ur").ToString
cmd5.ExecuteNonQuery()
con4.Close()
x += 1
End If
End While
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
I had the same problem.
I solved this by removing the Thread and calling the method directly

VB.NET DataSet Update

Why my set of codes didn't update in DataSet? Then it goes to Error. Please anyone check this code and point me out where I am missing. Thanks in advance!
Private Sub btnUpdate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnUpdate.Click
Dim conxMain As New SqlConnection("Data Source=SERVER;Initial Catalog=DBTest;Persist Security Info=True;User ID=username;Password=pwds")
Dim dadPurchaseInfo As New SqlDataAdapter
Dim dsPurchaseInfo As New DataSet1
Try
Dim dRow As DataRow
conxMain.Open()
Dim cmdSelectCommand As SqlCommand = New SqlCommand("SELECT * FROM Stock", conxMain)
cmdSelectCommand.CommandTimeout = 30
dadPurchaseInfo.SelectCommand = cmdSelectCommand
Dim builder As SqlCommandBuilder = New SqlCommandBuilder(dadPurchaseInfo)
dadPurchaseInfo.Fill(dsPurchaseInfo, "Stock")
For Each dRow In dsPurchaseInfo.Tables("Stock").Rows
If CInt(dRow.Item("StockID").ToString()) = 2 Then
dRow.Item("StockCode") = "Re-Fashion[G]"
End If
Next
dadPurchaseInfo.Update(dsPurchaseInfo, "Stock")
Catch ex As Exception
MsgBox("Error : ")
Finally
If dadPurchaseInfo IsNot Nothing Then
dadPurchaseInfo.Dispose()
End If
If dsPurchaseInfo IsNot Nothing Then
dsPurchaseInfo.Dispose()
End If
If conxMain IsNot Nothing Then
conxMain.Close()
conxMain.Dispose()
End If
End Try
End Sub
Does your condition in the loop get executed (set a break point!)? Where is the error thrown? What error?
Also, why does it use ToString at all? This seems redundant.
If CInt(dRow.Item("StockID")) = 2 Then
Should be enough.
Finally, you’re performing redundant cleanup:
If conxMain IsNot Nothing Then
conxMain.Close()
conxMain.Dispose()
End If
Dispose implies Close – no need to perform both operations:
Close and Dispose are functionally equivalent.
[Source: MSDN]
Does your dataAdapter has update command ?
(it looks like it doesn't - so it doesn't know what do to with update....)
Here is an Update Command example:(for an employee table with 3 columns - as listed below:
UPDATE [Employee]
SET [name] = #name
, [manager] = #manager
WHERE (([id] = #Original_id) AND
((#IsNull_name = 1 AND [name] IS NULL) OR
([name] = #Original_name)) AND
((#IsNull_manager = 1 AND [manager] IS NULL) OR
([manager] = #Original_manager)));
SELECT id
, name
, manager
FROM Employee
WHERE (id = #id)
You can see it is a general update that can handle changes in any field.
I got it from the error correction of my program by Konard Rudolph!
Private Sub btnUpdate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnUpdate.Click
Dim conxMain As New SqlConnection("Data Source=SERVER;Initial Catalog=DBTest;Persist Security Info=True;User ID=username;Password=pwds")
Dim dadPurchaseInfo As New SqlDataAdapter
Dim dsPurchaseInfo As New DataSet1
Try
Dim dRow As DataRow
conxMain.Open()
dadPurchaseInfo.SelectCommand = New SqlCommand("SELECT * FROM Stock", conxMain)
Dim builder As SqlCommandBuilder = New SqlCommandBuilder(dadPurchaseInfo)
dadPurchaseInfo.Fill(dsPurchaseInfo, "Stock")
For Each dRow In dsPurchaseInfo.Tables("Stock").Rows
If CInt(dRow.Item("StockID")) = 2 Then
dRow.Item("StockCode") = "Re-Fashion(H)"
End If
Next
dadPurchaseInfo.Update(dsPurchaseInfo, "Stock")
Catch ex As Exception
MsgBox("Error : " & vbCrLf & ex.Message)
Finally
If dadPurchaseInfo IsNot Nothing Then
dadPurchaseInfo.Dispose()
End If
If dsPurchaseInfo IsNot Nothing Then
dsPurchaseInfo.Dispose()
End If
If conxMain IsNot Nothing Then
conxMain.Dispose()
End If
End Try
End Sub
The above set of code work to update with DataSet! Thanks to stackoverflow community and who answered my question.
Here is ref:
How To Update a SQL Server Database by Using the SqlDataAdapter Object in Visual Basic .NET
How to update a database from a DataSet object by using Visual Basic .NET
p.s: Like o.k.w said : The Table must have primary key. Thanks o.k.w!
--MENU--
Dim login As New LoginClass
login.ShowDialog()
--CONEXION--
Private conec As SqlConnection
Dim stringCon As String = "Data Source= ;Initial Catalog=;Persist Security Info=True;User ID=;Password="
Public ReadOnly Property prConec() As Object
Get
Return conec
End Get
End Property
Public Sub Conectar()
Try
conec = New SqlConnection(stringCon)
If conec.State <> ConnectionState.Open Then
conec.Open()
End If
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub
--BUSCAR--
funciones.Conectar()
Dim coman As New SqlCommand("sp_cliente", funciones.prConec)
Dim dt As New DataTable
coman.CommandType = CommandType.StoredProcedure
coman.Parameters.Add("#i_operacion", SqlDbType.Char, 1, ParameterDirection.Input).Value = "B"
dt.Load(coman.ExecuteReader())
grdClientes.DataSource = dt
--INSERTAR--
funciones.Conectar()
Dim coman As New SqlCommand("sp_articulo", funciones.prConec)
coman.CommandType = CommandType.StoredProcedure
coman.Parameters.Add("#i_operacion", SqlDbType.Char, 1, ParameterDirection.Input).Value = "I"
coman.ExecuteNonQuery()
Buscar()
Limpiar()
--COMBO--
Dim dt As New DataTable
dt.Columns.Add("Codigo")
dt.Columns.Add("Descripcion")
Dim dr1 As DataRow = dt.NewRow
dr1.Item("Codigo") = "A"
dr1.Item("Descripcion") = "Activo"
dt.Rows.Add(dr1)
Dim dr2 As DataRow = dt.NewRow
dr2.Item("Codigo") = "I"
dr2.Item("Descripcion") = "Inactivo"
dt.Rows.Add(dr2)
cmbEstado.DataSource = dt
cmbEstado.ValueMember = "Codigo"
cmbEstado.DisplayMember = "Descripcion"
--GRIDVIEW--
--1--
Dim grdFila As DataGridViewRow = grdClientes.CurrentRow
txtCedula.Text = grdFila.Cells(0).Value
--2--
If DataGridProductos.CurrentCell.ColumnIndex = 0 Then
Dim FLstArticulos As New FLstArticulos
FLstArticulos.ShowDialog()
DataGridProductos.CurrentRow.Cells(0).Value = FLstArticulos.PrIdArticulo
End If
--GRIDVIEW.CELLENDEDIT--
If DataGridProductos.CurrentCell.ColumnIndex = 3 Then
Dim precio As New Double
Dim cantidad As New Double
precio = CDbl(grdRow.Cells(2).Value)
cantidad = CDbl(grdRow.Cells(3).Value)
DataGridProductos.CurrentRow.Cells(4).Value = PLTotalFilaItem(cantidad, precio)
PLCargaTotales()
End If
Sub PLCargaTotales()
Dim subTotal As Double
Dim iva As Double
For Each grd As DataGridViewRow In DataGridProductos.Rows
If Not String.IsNullOrEmpty(grd.Cells(4).Value) Then
subTotal = subTotal + CDbl(grd.Cells(4).Value)
End If
Next grd
txtSubtotal.Text = subTotal.ToString
iva = Decimal.Round(subTotal`enter code here` * 0.12)
txtIva.Text = iva.ToString
txtTotalPagar.Text = (subTotal + iva).ToString
End Sub