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 - vb.net

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

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

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

Performance improvement on vb.net code

I need to write 50 million records with 72 columns into text file, the file size is growing as 9.7gb .
I need to check each and every column length need to format as according to the length as defined in XML file.
Reading records from oracle one by one and checking the format and writing into text file.
To write 5 crores records it is taking more than 24 hours. how to increase the performance in the below code.
Dim valString As String = Nothing
Dim valName As String = Nothing
Dim valLength As String = Nothing
Dim valDataType As String = Nothing
Dim validationsArray As ArrayList = GetValidations(Directory.GetCurrentDirectory() + "\ReportFormat.xml")
Console.WriteLine("passed xml")
Dim k As Integer = 1
Try
Console.WriteLine(System.DateTime.Now())
Dim selectSql As String = "select * from table where
" record_date >= To_Date('01-01-2014','DD-MM-YYYY') and record_date <= To_Date('31-12-2014','DD-MM-YYYY')"
Dim dataTable As New DataTable
Dim oracleAccess As New OracleConnection(System.Configuration.ConfigurationManager.AppSettings("OracleConnection"))
Dim cmd As New OracleCommand()
cmd.Connection = oracleAccess
cmd.CommandType = CommandType.Text
cmd.CommandText = selectSql
oracleAccess.Open()
Dim Tablecolumns As New DataTable()
Using oracleAccess
Using writer = New StreamWriter(Directory.GetCurrentDirectory() + "\FileName.txt")
Using odr As OracleDataReader = cmd.ExecuteReader()
Dim sbHeaderData As New StringBuilder
For i As Integer = 0 To odr.FieldCount - 1
sbHeaderData.Append(odr.GetName(i))
sbHeaderData.Append("|")
Next
writer.WriteLine(sbHeaderData)
While odr.Read()
Dim sbColumnData As New StringBuilder
Dim values(odr.FieldCount - 1) As Object
Dim fieldCount As Integer = odr.GetValues(values)
For i As Integer = 0 To fieldCount - 1
Dim vals As Array = validationsArray(i).ToString.ToUpper.Split("|")
valName = vals(0).trim
valDataType = vals(1).trim
valLength = vals(2).trim
Select Case valDataType
Case "VARCHAR2"
If values(i).ToString().Length = valLength Then
sbColumnData.Append(values(i).ToString())
'sbColumnData.Append("|")
ElseIf values(i).ToString().Length > valLength Then
sbColumnData.Append(values(i).ToString().Substring(0, valLength))
'sbColumnData.Append("|")
Else
sbColumnData.Append(values(i).ToString().PadRight(valLength))
'sbColumnData.Append("|")
End If
Case "NUMERIC"
valLength = valLength.Substring(0, valLength.IndexOf(","))
If values(i).ToString().Length = valLength Then
sbColumnData.Append(values(i).ToString())
'sbColumnData.Append("|")
Else
sbColumnData.Append(values(i).ToString().PadLeft(valLength, "0"c))
'sbColumnData.Append("|")
End If
'sbColumnData.Append((values(i).ToString()))
End Select
Next
writer.WriteLine(sbColumnData)
k = k + 1
Console.WriteLine(k)
End While
End Using
writer.WriteLine(System.DateTime.Now())
End Using
End Using
Console.WriteLine(System.DateTime.Now())
'Dim Adpt As New OracleDataAdapter(selectSql, oracleAccess)
'Adpt.Fill(dataTable)
Return Tablecolumns
Catch ex As Exception
Console.WriteLine(System.DateTime.Now())
Console.WriteLine("Error: " & ex.Message)
Console.ReadLine()
Return Nothing
End Try

How to move to next row in dataset and display in hyperlink

I'm writing an email application that will be used to send HTML news articles to clients.
I'm using a dataset to return the headlines to display to the client. When I loop through the dataset the the latest record is returned but latest headline link is not displayed. So the outputted HTML is the same headline everytime, which is the first record in the dataset. How do I move to the next record in the data set and get the outputted HTML to display the next/correct headline?
Here is a sample of my code:
'Code to populate dataset
Public Function GetHeadline(ByVal ArticleID As Integer) As DataSet
Try
Dim objConn As SqlConnection = New SqlConnection()
objConn.ConnectionString = myConnectionString
objConn.Open()
ds = New DataSet
ds.Clear()
Dim sqlCommand As String = "SomeSql"
Dim objCmd As SqlCommand = New SqlCommand(sqlCommand, objConn)
Dim dataAdapter As SqlDataAdapter = New SqlDataAdapter(objCmd)
dataAdapter.Fill(ds)
Catch ex As Exception
MsgBox(ex.ToString)
GetHeadline = Nothing
End Try
Return ds
End Function
'Code to populate link
If GroupID = 4 Then
iLocation1 = HTMLbody.IndexOf("{!HeadlineID")
While iLocation1 > 0
iLocation2 = HTMLbody.IndexOf("}", iLocation1)
sHeadLineTag = HTMLbody.Substring(iLocation1 + 1, iLocation2 - iLocation1 - 1)
dtReport = clsGlobal.globalReportCatalog.GetHeadline2()
clsGlobal.globalReportCatalog.SetHeadlinePropertiesFromRow(dtReport.Rows(0))
With clsGlobal.globalReportCatalog
For i As Integer = 0 To dtReport.Rows.Count
If i < dtReport.Rows.Count - 1 Then
i = i + 1
End If
Dim ID As Integer = dtReport.Rows(i)("ArticleID")
sHyperTag = "" & .HeadlineReportName & " - " & .HeadlineTitle & ""
sHeadlineDescription = .HeadlineDescription
HTMLbody = HTMLbody.Replace("{!Report.Description}", sHeadlineDescription)
Next
End With
I don't see why you need
For i As Integer = 0 To dtReport.Rows.Count
If i < dtReport.Rows.Count - 1 Then
i = i + 1
End If
Can't you use
Dim ID As Integer = dtReport.Rows(dtReport.Rows.Count - 1)("ArticleID")
or was there supposed to be a row movenext in the loop you forgot?