how to add list in `DATAGRIDVIEW` with combobox on runtime - vb.net

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

Related

Problem with my usercontrol listview fill data from msaccess

I created listview ms activex by vb.net to my access database
i add that code in vb.net to fill my listview
Public Sub FillListview(ByVal CurrntDb As String)
Dim conn As OleDbConnection
Dim cmd As OleDbCommand
Dim da As OleDbDataAdapter
Dim ds As DataSet
Dim itemcoll(100) As String
ListView1.View = View.Details
ListView1.GridLines = True
ListView1.Items.Clear()
conn = New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source =" & CurrntDb)
Dim strQ As String = String.Empty
strQ = "SELECT Accounts.ID AS [م], Customers.Customer AS [العميل], Accounts.Debit AS [مدين], Accounts.Credit AS [دائن], Accounts.Dates AS [التاريخ], Accounts.Notes AS [البيان] FROM Accounts INNER JOIN Customers ON Accounts.Customer_ID = Customers.Customer_ID;"
cmd = New OleDbCommand(strQ, conn)
da = New OleDbDataAdapter(cmd)
ds = New DataSet
conn.Open()
da.Fill(ds)
Dim i As Integer = 0
Dim j As Integer = 0
' adding the columns in ListView
For i = 0 To ds.Tables(0).Columns.Count - 1
ListView1.Columns.Add(ds.Tables(0).Columns(i).ColumnName.ToString())
Next
'Now adding the Items in Listview
For i = 0 To ds.Tables(0).Rows.Count - 1
For j = 0 To ds.Tables(0).Columns.Count - 1
itemcoll(j) = ds.Tables(0).Rows(i)(j).ToString()
Next
Dim lvi As New ListViewItem(itemcoll)
ListView1.Items.Add(lvi)
ListView1.Refresh()
Next
conn.Close()
End Sub
and regestir it in my access database
and call it in access code by that code
Dim xlist As New AForTestListviewBySedo.UserControl1
Call xlist.FillListview("C:\Users\Elsayed\Desktop\New folder\mydb.accdb")
but they give me nothing not error but nothing
I tested that code in usercontrol by add button in it
button works good
What can I do ?
the solution is with my code in access to call record
i need to set object at first
the correct code is
Option Explicit
Option Compare Database
Public listv As MsAccessListviewACX1_00.UCBySedo
Public Sub LoadListview()
Set listv = Me.UCBySedo9.Object
listv.FillListview ("C:\Users\Elsayed\Desktop\New folder\mydb.accdb")
End Sub
Private Sub Command115_Click()
Call LoadListview
End Sub

Trying to add a list of suppliers in an array and then i am adding it to listbox and combobox using `.addrange` but i am receiving error

I retrieved list of suppliers from database and saved it in an array TOTAL_SUPPLIERS_ARRAY NOW i am trying it to add in the listbox or combobox but it shows an error on runtime saying "VALUE CAN NOT BE NULL" but if i try to add it with an loop it works properly why is it not working with .addrange ?
Sub GET_SUPPLIERS_DETAILS()
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
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
ListBox1.Items.AddRange(TOTAL_SUPPLIERS_ARRAY)
ComboBox1.Items.AddRange(TOTAL_SUPPLIERS_ARRAY)
For I As Integer = 0 To UBound(TOTAL_SUPPLIERS_ARRAY) - 1
TextBox1.Text += TOTAL_SUPPLIERS_ARRAY(I) & " - "
Next I
End Sub
This part works only as i added it through a loop
For I As Integer = 0 To UBound(TOTAL_SUPPLIERS_ARRAY) - 1
TextBox1.Text += TOTAL_SUPPLIERS_ARRAY(I) & " - "
Next I
listbox.addrange command and combobox.addrange command not working
Here you have an issue TOTAL_SUPPLIERS_ARRAY(TOTAL_SUPPLIERS). Array declared in VB - array(upper-bound). Upper bound is 1 less than count. So, you should do TOTAL_SUPPLIERS_ARRAY(TOTAL_SUPPLIERS - 1).
But why struggle? Just use list
Dim myList as New List(of String)
While dr.Read()
myList.Add(dr("Supplier_Name").ToString())
Loop
And then, if you still need array, you can use LINQ - myList.ToArray
ListBox1.DataSource = myList.ToArray()

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

how to Flip dataset and display in datagridview

I try to flip dataset to display column as rows by using this code but it does not work :
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button.Click
Dim ds2 As New DataSet
Dim dt2 As New DataTable
Dim com1 As String = "select col1,col2,col3 from table1"
ds2 = FlipDataSet(ds2)
Dim dp As New SqlDataAdapter(com1, conn)
dp.Fill(dt2)
DGV_lev1.DataSource = dt2.DefaultView
End Sub
and use this function to flip dataset :
Private Function FlipDataSet(old_DataSet As DataSet) As DataSet
Dim ds As New DataSet()
For Each dt As DataTable In old_DataSet.Tables
Dim table As New DataTable()
For i As Integer = 0 To dt.Rows.Count
table.Columns.Add(Convert.ToString(i))
table.Columns(0).ColumnName = "Fields"
If i = 0 Then
Continue For
Else
table.Columns(i).ColumnName = "Customer " & i
End If
Next
Dim r As DataRow
For k As Integer = 0 To dt.Columns.Count - 1
r = table.NewRow()
r(0) = dt.Columns(k).ToString()
For j As Integer = 1 To dt.Rows.Count
r(j) = dt.Rows(j - 1)(k)
Next
table.Rows.Add(r)
Next
ds.Tables.Add(table)
Next
Return ds
End Function
to make datagirdview display from this :
to this :
can anyone help me
thank you
Try this, it worked in a quick test I did:
Private Function Transpose(ByVal table As DataTable) As DataTable
Dim flippedTable As New DataTable
'creates as many columns as rows in source table
flippedTable.Columns.AddRange(
table.Select.Select(
Function(dr) New DataColumn("col" & table.Rows.IndexOf(dr), GetType(Object))
).ToArray)
'iterates columns in source table
For Each dc As DataColumn In table.Columns
'get array of values of column in each row and add as new row in target table
flippedTable.Rows.Add(table.Select.Select(Function(dr) dr(dc)).ToArray)
Next
Return flippedTable
End Function

while filling data grid view using sql reader application getting slow

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()