Splitting listviews items help needed - vb.net

I have some code that loops through a listview and puts the values into 'output1' & 'output2'. However, what is happening is that the results are strung together like thus: 0307NG77775660NG7778. How do I split so that I can include in access db.
There are 2 columns in the listview and they contain values in the format of:
1st row 0307 - NG7777, 2nd row 5660 - 7778 etc. This is a desktop winforms code. Thanks
Dim BoxList As New List(Of String)
Dim BoxItem As String
Dim CustRefList As New List(Of String)
Dim CustRef As String
For Each item As ListViewItem In Me.lvSelectedItems.Items
Dim box As String = item.Text
BoxItem = item.SubItems.Item(1).Text
BoxList.Add(box)
output2 += BoxItem
Dim cust As String = item.Text
CustRef = item.SubItems.Item(1).Text
CustRefList.Add(cust)
output1 += CustRef
Next
output = String.Join(" "c, BoxList.ToArray(), CustRefList.ToArray())
Dim cmd As OleDbCommand = New OleDbCommand("Insert into Temp (temp, [class]) Values ('" & output1 & "', '" & output2 & "')", oledbCnn)
dr = cmd.ExecuteReader

Make username a List(Of String), then just do:
usernameList.Add(username) 'instead of output1 += username
When done with the loop, do this:
output1 = String.Join(" "c, usernameList.ToArray())
You can pick a join character of your choice (if you don't like spaces " ").
EDIT: Example:
Dim usernameList As New List(Of String)
Dim session As String
For Each item As ListViewItem In Me.lvSelectedItems.Items
Dim username As String = item.Text
session = item.SubItems.Item(1).Text
usernameList.Add(username)
output2 += session
Next
output1 = String.Join(" "c, usernameList.ToArray())

Related

Looking for a way to populate listview from String array

I have a problem populating a ListView with an I have created. All of the data goes to one column instead of rows. Could you help me to populate it correctly?
Dim finalas() As String = arrf.ToArray(GetType(System.String))
For Each element As String In finalas
Dim item As New ListViewItem(element)
ListView1.Items.Add(item)
Next
I have found a solution myself, if some one needs it, here you go:
Sub readTextFile()
' Create new StreamReader instance with Using block.
Dim path As String = "D:\data.txt"
Dim st() As String = File.ReadAllLines(path) 'read the file into array of
Dim p_1 As String = ""
Dim p_2 As String = ""
Dim arrl As Integer = 11
For Each itm As String In st 'loop the array of string item by item
Dim Arr() As String = itm.Split(New String() {" "}, StringSplitOptions.RemoveEmptyEntries) 'split the string
Dim name() As String = itm.Split(New String() {"'"}, StringSplitOptions.RemoveEmptyEntries)
' Arr.Skip(1).ToArray -nenuskaito pirmojo
' Arr = Arr.Take(Arr.Length - 1).ToArray - nenuskaito paskutinio
'galutinis array
p_1 = Arr(1)
p_2 = Arr(2)
Dim finarr As New List(Of String)
finarr.Add(p_1)
finarr.Add(p_2)
finarr.Add(name(1))
For i As Integer = 4 To arrl
finarr.Add(Arr(((Arr.Length - 1) - arrl) + i))
Next
'MsgBox(finarr(0) & finarr(1) & finarr(2) & finarr(3) & finarr(4) & finarr(5) & finarr(6) & finarr(7) & finarr(8) & finarr(9) & finarr(10))
Dim items As New List(Of ListViewItem)
Dim lvItem = New ListViewItem(finarr(0))
For i = 1 To 10
lvItem.SubItems.Add(finarr(i))
Next i
items.Add(lvItem)
ListView1.Items.AddRange(items.ToArray)
Next
Return
End Sub

Streamreader read next line if empty row

I have a problem when i want to use streamreader readline by line my text file. The streamreader i using is by taking the substring, but when it comes to empty rows it pop up this error message "Index and length must refer to a location within the string". It is not exactly empty row or line, but it contains this thing "ÐôÐ#(ôd". How to skip or ignore or delete the row that not have appropriate line in text file?This is my code
For Each finalname In filenames
row2 = 1
Using reader As New StreamReader(finalname)
Do Until reader.EndOfStream
Dim line As String = reader.ReadLine
Dim datetimestring As String = line.Substring(0, 22)
datetimestring = datetimestring.Replace("""", "").Trim()
datetimestring = datetimestring.Replace("-", "").Trim()
Dim format As String = "dd/MM/yyyy hh:mm:ss tt"
Dim time As DateTime = DateTime.Parse(datetimestring)
Dim Dt = time.ToString(format)
'Dim dtime As DateTime = DateTime.Parse(Dt)
Dim c As String = line.Substring(22)
c = c.Replace("-", "").Trim()
Dim cmd1 As New SqlCommand("insert into table5([time] , [process], [oven], [line]) values ( #line , #line1, '" & oven & "', '" & row2 & "')", con1)
cmd1.Parameters.Add("#line", SqlDbType.DateTime).Value = time
cmd1.Parameters.Add("#line1", SqlDbType.NVarChar).Value = c
con1.Open()
cmd1.ExecuteNonQuery()
con1.Close()
row2 = row2 + 1
Loop
oven = oven + 2
Dim str20 As String = "data source=10.239.213.40;uid=sa;pwd=Win32API;database=mbi"
Dim con20 As New SqlConnection(str20)
Dim com20 As String = "select top 9 * from table5 where process like '%Load lot clicked%' or process like '%''QCheck'' Button%' or process like '%''Start'' Button%' or process like '%Run Proc%' or process like '%Run Bin2 clicked%' or process like '%Started with Double click%' and oven ='2' order by oven, line desc"
Dim Adpt20 As New SqlDataAdapter(com20, con1)
Dim ds2 As New DataSet()
Adpt20.Fill(ds2, "table5")
DataGridView1.DataSource = ds2.Tables(0)
End Using
Next
Try this
Dim line As String = reader.ReadLine
If(String.ISNullorWhiteSpace(line) = false Then
Dim datetimestring As String = line.Substring(0, 22)
datetimestring = datetimestring.Replace("""", "").Trim()
datetimestring = datetimestring.Replace("-", "").Trim()
Dim format As String = "dd/MM/yyyy hh:mm:ss tt"
Dim time As DateTime = DateTime.Parse(datetimestring)
Dim Dt = time.ToString(format)
'Dim dtime As DateTime = DateTime.Parse(Dt)
Dim c As String = line.Substring(22)
c = c.Replace("-", "").Trim()
Dim cmd1 As New SqlCommand("insert into table5([time] , [process], [oven], [line]) values ( #line , #line1, '" & oven & "', '" & row2 & "')", con1)
cmd1.Parameters.Add("#line", SqlDbType.DateTime).Value = time
cmd1.Parameters.Add("#line1", SqlDbType.NVarChar).Value = c
con1.Open()
cmd1.ExecuteNonQuery()
con1.Close()
row2 = row2 + 1
End If
If line.Substring is the issue then check with something like this
Dim lineLength As Int = line.Length()
Dim datetimestring As String =If(line.Substring(0, 22) = Null, "", ine.Substring(0, 22))
Dim datetimestring As String =If(lineLength < 22, "", line.Substring(0, 22))
I wouldn't use SubString function, as you noted when a line is shorter than 22 characters the program will crash.
Typically I will subdivide or split the line into different parts by using Split function, for example:
dim ast() as string = line.split("XXX")
then extract the specific string from it:
datetimestring = ast(0)
this, of course, requires the parts are seperated by common delimiters, such as ',' or empty spaces, etc.
Also, add additional condition after reading the line, for example:
Dim line As String = reader.ReadLine
If String.ISNullorWhiteSpace(line) orelse line.length < 10 Then continue do
Do Until reader.EndOfStream
Dim line As String = reader.ReadLine
If Not String.IsNullOrWhiteSpace(line) AndAlso Not line.Length < 22 Then
'put the rest of your do-loop code here
End If
Loop

add listbox values to access database windows form application

I have a calculator with two textboxes where the user puts a number in each one. They then click a plus, minus, divide, or multiply button and it does that function to the numbers. These numbers are saved to a listbox called listbox1. When the user clicks to display the results, the listbox is populated with all their saved values, and the application is SUPPOSED to save the listbox items to an access database. it is not working. Below is my code, where numFirst is the name of a category in the database table:
Private Sub btnDisplay_Click(sender As Object, e As EventArgs) Handles
btnDisplay.Click
ListBox1.Items.Clear()
For arrayindex As Integer = 0 To intarrayCount - 1
ListBox1.Items.Add(Input(arrayindex))
ListBox1.Text = Convert.ToString(ListBox1.Items.Item(arrayindex))
Next arrayindex
Dim query As String = "SELECT * FROM wk6"
Dim connectionString As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\helse_000\Desktop\APU\VB Advanced\week4\ENTD461_wk4_Andrew_Helsel\ENTD461_wk2_Andrew_Helsel\calculator.mdb"
Dim command As OleDbCommand = New OleDbCommand
Dim var1 As String = Convert.ToString(ListBox1.Items.Item(0))
command.CommandText = "INSERT into wk6 (numFirst) VALUES (" + var1 + ")"
Figured it out, removed the select all query string and made my textbox fields into parameters after modifying their results a bit to fit the format I needed for the table.
For i As Integer = 0 To ListBox1.Items.Count - 1
Dim firstString As String = Convert.ToString(ListBox1.Items.Item(i))
Dim leftPart As String = firstString.Split(Convert.ToChar
(strButtonSelected))(0)
Dim rightPart As String = firstString.Split(Convert.ToChar("="))(1)
Dim a As Integer = firstString.IndexOf(strButtonSelected)
Dim b As Integer = firstString.IndexOf("=")
Dim secNum = firstString.Substring(a + 1, b - 4)
secNum = secNum.Trim
Dim conn As OleDbConnection = New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;
Data Source=C:\Users\helse_000\Desktop\APU\VB Advanced\week4\ENTD461_wk4_Andrew_Helsel\ENTD461_wk2_Andrew_Helsel\calculator.mdb")
Dim command As OleDbCommand = New OleDbCommand
Dim cmdstring As String = "INSERT INTO wk6 (numFirst, numSecond, Operator, equals, Answer)" + " VALUES (#firstName,#lastName,#Operator,#equals,#answer)"
command = New OleDbCommand(cmdstring, conn)
command.Parameters.AddWithValue("#firstName", leftPart)
command.Parameters.AddWithValue("#lastName", secNum)
command.Parameters.AddWithValue("#Operator", strButtonSelected)
command.Parameters.AddWithValue("#equals", "=")
command.Parameters.AddWithValue("#answer", rightPart)
conn.Open()
command.ExecuteNonQuery()
conn.Close()

LDAP departmentnumber query

I am attempting to query a list of users that are assigned to a specific departmentnumber in LDAP, which I know should be a list of about 100. The below code only pulls back one member (which last name starts with T, so in my mind it seems like it's only returning the last value):
Dim userIds As IEnumerable(Of String) = {"7871"}
For Each i As String In userIds
Dim de As New DirectoryEntry("LDAP://test.net:389/DC=test,DC=net")
Dim LdapFilter As String = "(departmentNumber=" & i & ")"
Dim searcher As New DirectorySearcher(de, LdapFilter)
Dim result As SearchResult = searcher.FindOne()
Dim res As SearchResultCollection = searcher.FindAll()
Dim item As ListViewItem = ListView1.Items.Add(i)
item.SubItems.Add(result.Properties("givenName")(0).ToString())
item.SubItems.Add(result.Properties("cn")(0).ToString())
item.SubItems.Add(result.Properties("userPrincipalName")(0).ToString())
Next
this works:
Dim userIds As IEnumerable(Of String) = {"7871"}
For Each i As String In userIds
Dim de As New DirectoryEntry("LDAP://test.net:389/DC=test,DC=net")
Dim LdapFilter As String = "(departmentNumber=" & i & ")"
Dim searcher As New DirectorySearcher(de, LdapFilter)
Dim result As SearchResult
Dim res As SearchResultCollection = searcher.FindAll()
For Each result In res
Dim item As ListViewItem = ListView1.Items.Add(i)
item.SubItems.Add(result.Properties("givenName")(0).ToString())
item.SubItems.Add(result.Properties("cn")(0).ToString())
item.SubItems.Add(result.Properties("userPrincipalName")(0).ToString())
Next
Next

VB.NET create datatable?

I am trying to create a datatable in VB.NET, but when I output a row from this table it shows: "System.Data.DataRow".
I have compared my code to several websites and it seems correct. However if I instead Response.Write these values they display correctly.
So here is my code:
Sub Page_Load(Sender as Object, E as EventArgs)
If Not IsPostback Then
...
End If
Main
End Sub
Sub Main()
Dim FirstMonthDate As Date = CDate("1/1/" & dYear.SelectedValue)
Dim LastMonthDate As Date = GlobalFunctions.GlobalF.MonthLastDate(dYear.SelectedValue & "-" & dEndMonth.SelectedValue & "-1")
Dim TheGroup As String
Dim LastWeek As String
Dim FirstWeek As String
Dim dLastWeek As Date
Dim dFirstWeek As Date
Dim iWeek As String
Dim commandstring As String = "SELECT cast(DateDiff(wk, '1/1/2011', '" & LastMonthDate & "') as varchar(30)) AS SELECTED_WEEK "
Dim DSDateData As New System.Data.DataSet
DSDateData = GlobalFunctions.GlobalF.GetDevSQLServerDataSet(commandstring)
Dim dRow As DataRow
For Each dRow In DSDateData.Tables(0).Rows
iWeek = dRow("SELECTED_WEEK")
Next
Dim FirstYearDate As Date = CDate("1/1/" & dYear.SelectedValue)
commandstring = "SELECT DateAdd(ww, " & iWeek & ", '" & FirstYearDate & "') AS LAST_WEEK "
Dim DSDateData2 As New System.Data.DataSet
DSDateData2 = GlobalFunctions.GlobalF.GetDevSQLServerDataSet(commandstring)
For Each dRow In DSDateData2.Tables(0).Rows
LastWeek = dRow("LAST_WEEK")
Next
dLastWeek = CDate(LastWeek)
commandstring = "SELECT DATEADD(dd, -1, DATEADD(wk, DATEDIFF(wk,0, dateadd(dd,6-datepart(day,'" & LastMonthDate & "'),'" & LastMonthDate & "') ), 0)) AS FIRST_WEEK "
Dim DSDateData3 As New System.Data.DataSet
DSDateData3 = GlobalFunctions.GlobalF.GetDevSQLServerDataSet(commandstring)
For Each dRow In DSDateData3.Tables(0).Rows
FirstWeek = dRow("FIRST_WEEK")
Next
dFirstWeek = CDate(FirstWeek)
dFirstWeek = DateAdd(DateInterval.WeekOfYear, -1, dFirstWeek)
Dim arrDayYear As New ArrayList()
Dim dFirstDay As New Date
Dim arrList As ArrayList = New ArrayList()
Dim dt2 As New DataTable
Dim sWeek As DataColumn = New DataColumn("sWeek")
sWeek.DataType = System.Type.GetType("System.String")
Dim sDay As DataColumn = New DataColumn("sDay")
sDay.DataType = System.Type.GetType("System.String")
dt2.Columns.Add(sWeek)
dt2.Columns.Add(sDay)
Response.Write("NW1")
Dim dr As DataRow
dr = dt2.NewRow()
dr("sWeek") = "New week"
dr("sDay") = "New day"
dt2.Rows.Add(dr)
Response.Write(dr)
Response.Write("<br>")
dFirstDay = dFirstDay.AddDays(1)
...
End Sub
...
It's this last Response.Write that is causing the "System.Data.DataRow". But the Response.Write before this (NW1) does print. So what am I doing wrong?
Your code is correct.
Calling Response.Write(dr) prints dr.ToString().
Since DataRow doesn't override ToString(), it jsut returns the typename.
You probably want to prin the value of a column.
You must iterate the data rows or select a specific data row. Iterating and outputing the values would be like so:
//c#
foreach (DataRow row in dt.Rows)
{
foreach (DataColumn col in dt.Columns)
Console.WriteLine(row[col]);
}
//VB.Net
For Each (row As DataRow In dt.Rows)
For Each (col As DataColumn In dt.Columns)
Console.WriteLine(row[col])
Next
Next
To print just the first row:
DataRow row = dt.Rows[0];
foreach (DataColumn col in row.Columns)
Console.WriteLine(row[col]);
Response.Write() Needs a string, so it is converting your variable (dr) to a string. The default "toString" method just uses the name of the class. In this case "System.Data.DataRow"
It seems like you might want to loop over the row and output each value individually something like...
For Each element In dr.ItemArray
Response.Write(element)
Next
Response.Write("<br>")