I have list of columns in DataTable to be added in list view. I have specified to the listview of columns in the order to appear and Datas as well.
EmailAddress Subject RecievedDate
cd#cd.in Hello 02/06/2011 23:00
This the format to appear.Please anyone can help on this
EDIT:
Code so far:
For i = 0 To objDataTable.Rows.Count drow = objDataTable.Rows(i)
Dim lvwItem As ListViewItem = New lvwItem(drow("SenderEmail"))
'lvwItem.SubItems.Add(drow("SenderEmail"))
lvwItem.SubItems.Add(drow("EmailSubject"))
lvwItem.SubItems.Add(drow("RecievedDate").ToString())
lvwItem.SubItems.Add(drow("AssignedTo").ToString())
LOV.Items.Add(lvwItem)
Next
Your code sample looks almost correct. One error is this line:
Dim lvwItem As ListViewItem = New lvwItem(drow("SenderEmail"))
This should be:
Dim lvwItem As ListViewItem = New ListViewItem(drow("SenderEmail").ToString())
Apart from that you need to make sure your listview is in details view and you actually have the columns you require (otherwise nothing will be shown when in details view):
With listview1
.View = View.Details
.Columns.Add("Email Address")
.Columns.Add("Subject")
.Columns.Add("Recived Date")
'etc
End With
One other small issue is This line:
For i = 0 To objDataTable.Rows.Count
Should be
For i = 0 To objDataTable.Rows.Count - 1
Related
I have two listview controls, each having the same column headers. Listview1 contains the master data table and listview2 has a much smaller set of data that I need to add to the Master in Listview1. I can add this new data to the bottom of the main data in Listview1 using the AddRange option, but I need to add it to the top of the data in Listview1 but cannot see how.
If anyone can help I would appreciate it. Thank you in advance.
Thank you for your comments, which I have taken on board.
Let me add some more detail and some code. The data in Listview2 is a monthly csv file input which I read into the Listview2. The data is a set of details with the first field being the date, the most recent date at the top of data. I package this data as an array and attempt to load in into listview1, the master file, with the exact same fields and date order. Here is the code I have used to load the csv and the code to place the packaged data into Listview1. The only problem with this is, it places the data at the end of the current file in Listview1, so it would be out of sequence, so I am trying to place it at the top of the current file in Listview1.
' load the file into listview with this quick routine.
Dim CSVTest As List(Of String) = New List(Of String)
CSVTest = File.ReadAllLines(ImportDirname).ToList
Dim ColNames As List(Of ColumnHeader) = New List(Of ColumnHeader)
Dim ColumnArray() As String = CSVTest(0).Split(",")
For i = 0 To ColumnArray.Count - 1
ColNames.Add(New ColumnHeader)
ColNames(i).Name = ColumnArray(i)
ColNames(i).Text = ColumnArray(i)
Next
ListView2.Columns.AddRange(ColNames.ToArray)
'This adds the rest of the data from the file to the listview.
For I = 1 To CSVTest.Count - 1
Dim col() As String = CSVTest(I).Split(",")
Dim NewLVItem As ListViewItem = New ListViewItem(col(0))
NewLVItem.Name = col(0)
For j = 1 To col.Count - 1
NewLVItem.SubItems.Add(col(j))
Next
ListView2.Items.Add(NewLVItem)
Next (I)
' this adds the range to the bottom of the listview data
' - not what is required. I need it at the top !!!!!
Dim Items(ListView2.Items.Count - 1) As ListViewItem
For i As Integer = 0 To ListView2.Items.Count - 1
Items(i) = CType(ListView2.Items(i).Clone, ListViewItem)
Next
ListView1.Items.AddRange(Items)
Again if anyone can help I would be grateful.
Try Something Like This
With lst1. Items.**Insert**(0, "Sample", 0)
.SubItems.Add(2)
.SubItems.Add(3)
.SubItems.Add(4)
.SubItems.Add(5)
.SubItems.Add(6)
.SubItems.Add(listDownload.Count - 1)
End With
Hope this can help you
I've checked for hours but I can't seem to find anything to help.
I want to loop through tables and columns from a dataset and use the column name in a combobox.items.add() line, however the eventual goal is to fill the combobox from the dataset itself possibly in a combobox.datasource line.
The first problem is that I can't get the code correct to setup the combobox control where it allows me to use .items.add("") and in extension .datasource
Error Message = "Object reference not set to an instance of an object"
dstcopt is the dataset from a oledbDataAdapter .fill(dstcopt,"table") line (which returns correct values)
tc_opt is a tab name on a tab control where the comboboxes are
For Each dstable In dstcopt.Tables
For Each dscolumn In dstable.Columns
Dim colName As String = dscolumn.ToString
MsgBox(colName) 'This retuns "aantigen"
Dim cb As ComboBox = Me.tc_opt.Controls("cb_" & colName)
cb.Items.Add(colName)
'cb_aantigen.DataSource = dstcopt.Tables(dstable.ToString)
'cb_aantigen.DisplayMember = "aantigen"
'cb_atarget.DataSource = dstcopt.Tables(dstable.ToString)
'cb_atarget.DisplayMember = "atarget"
Next
Next
The second problem comes when I do it manually (which works) using the exact combobox names cb_aantigen and cb_atarget as seen in the comments.
The problem is that once the form is loaded and the cb's are filled with the correct values, I can't change the value in any single cb individually, when I change one value it changes them all (there is 15 comboboxes in total) I know this is down to using a dataset, but I don't know away to 'unlink them from each other or the dataset'
Not sure if I need to split this into 2 questions, but help on either problem would be appreciated.
EDIT:
After looking at only this section of code for a day. This is what I have come up with to tackle both the problems at once.
The combobox control not working was down to using a tab tc_opt instead of a groupbox gp_anti
The issue with splitting the dataset up into individual comboboxes, I've worked around by taking the value of each cell in the database and adding it separately, probably a better way to do it though
For Each dstable As DataTable In dstcopt.Tables
For Each dscolumn As DataColumn In dstable.Columns
Dim colName As String = dscolumn.ToString
Dim cb(2) As ComboBox
cb(0) = CType(Me.gp_anti.Controls("cb_" & colName), ComboBox)
cb(1) = CType(Me.gp_rec.Controls("cb_" & colName), ComboBox)
cb(2) = CType(Me.gp_nat.Controls("cb_" & colName), ComboBox)
For icb = 0 To cb.Count - 1
If Not (IsNothing(cb(icb))) Then
For irow = 0 To dstable.Rows.Count - 1
If dstable.Rows(irow)(colName).ToString <> Nothing Then
Dim icbitemdupe As Boolean = False
If cb(icb).Items.Contains(dstable.Rows(irow)(colName).ToString) Then
icbitemdupe = True
End If
If icbitemdupe = False Then
cb(icb).Items.Add(dstable.Rows(irow)(colName).ToString)
End If
End If
Next
End If
Next
Next
Next
I have a problem where when I add a subitem to the listview all the subitems go out to each of the columns, what I am trying to do is have 4 columns with the results going vertically down each column, I am going to post the code I am using for 1 of the columns so as not to have too much crap on the page here.
Dim source As String = (New Net.WebClient).DownloadString("http://arma.newagerp.com/bb.php")
ListView1.Columns.Add("Deaths")
Dim formula2 As String = "<td><div class='deaths'>([^<]*)</td></div>"
Dim item2 As New ListViewItem("item2", 1)
For Each item As Match In (New Regex(formula2)).Matches(source)
item2.SubItems.Add(item.Groups(1).Value)
Next
ListView1.Items.AddRange(New ListViewItem() {item2})
if you want more code just tell me but this is working and its just the same for the other 3, the other 3 are just player names, score and time in the same listview.
If i undrstand your question right, you want to add next row after passing the value to all four column? if this is right then have a look example code below.
While (Condition)
Dim objItem As ListViewItem
objItem = lv_Details.Items.Add("")
With objItem
.SubItems.Add("")
.SubItems.Add("")
.SubItems.Add("")
.SubItems.Add("")
End With
End While
Hope this will help. :)
I am confused being a relatively new user to vb.net. Why my listview is not amending the value in the list? If I may, so I have a correct working of how listview displays its data from database. I have a general question in addition to my code problem.
I have five columns in my listview (0-4). Am I correct in saying that if my access database contained say 10 fields but I only needed to display five of them but one of them was field (9), then would code the list like my code below, which is not changing the value and will only display the list if I remove the 'else' statement.
What is the error? Many thanks
UPDATED CODE:
oledbCnn.ConnectionString = My.Settings.storageConnectionString
oledbCnn.Open()
'drcount = Convert.ToInt32(dr("RowCount"))
sql = "Select TOP 100 * from Requests ORDER BY [Date-time received] DESC"
Debug.Print(sql)
Dim oledbCmd As OleDbCommand = New OleDbCommand(sql, oledbCnn)
Using dr = oledbCmd.ExecuteReader()
'clear items in the list before populating with new values
'lvRequests.Items.Clear()
While dr.Read()
If dr.HasRows Then
Dim LVI As New ListViewItem
With LVI
.Text = dr(0).ToString()
.UseItemStyleForSubItems = False
.SubItems.Add(CDate(dr(5)).ToShortDateString())
.SubItems.Add(dr(1).ToString())
.SubItems.Add(dr(3).ToString())
If dr(3).ToString = "D" Then
.SubItems(3).Text = "Destroyed"
ElseIf dr(3).ToString = "O" Then
.SubItems(3).Text = "Out"
ElseIf dr(3).ToString = "I" Then
.SubItems(3).Text = "Intake"
End If
.SubItems.Add(dr(9).ToString())
If dr(9).ToString = "DEMO" Then
.SubItems(9).Text = "Done"
End If
End With
lvRequests.Items.Add(LVI)
lvcount += 1
End If
End While
End Using
There is not enough info to be really sure what is going on. It appears that you pull 10 columns from the DB, but if you only post 5 of them to the LV, then there should only be 5 subitems. So this is wrong:
If dr(9).ToString() = "DEMO" Then
lvRequests.Items(lvRequests.Items.Count - 1).SubItems(9).Text = "Done"
' should probably be:
If dr(9).ToString() = "DEMO" Then
lvRequests.Items(lvRequests.Items.Count - 1).SubItems(4).Text = "Done"
What might make it clearer at least in code would be to use Names for the subitems. If you instance a SubItem object rather than use a default constructor, you can assign a name and reference them that way instead:
Dim si As New ListViewItem.ListViewSubItem
With si
.Text = dr(X).ToString ' dunno whats in there
' this is probably not exactly right, but give the SubItem
' the same name as the db column
.Name = dr.Table.Columns(X).ColumnName
End With
thisItem.SubItems.Add(si) ' add sub to Item collection
Now, your code can use the name rather than index:
If dr(9).ToString() = "DEMO" Then
lvReq.Items(lvReq.Items.Count - 1).SubItems("TheColumnName").Text = "Done"
it no longer really matters how many columns or subitems there are. The ListViewItem.SubItems collection does not require sub item names to be unique, so it is possible to end up with 2 with the same name, but if you map from the DR/DT/DB correctly, it should take care of itself.
If the LV is bound to the datasource (you did not say), then there could be as many SubItems as db/datasource columns (never actually used an LV that way).
I have a table named users which has the following columns in it
User_id,user_name,user_pwd,First_Name,Middle_Name,Last_Name and user_type.
I have dataset named dst and created a table called user in the dataset. Now I want to populate listbox with user_Name, First_Name, Last_name of each and every row in the table user.
I am able to add one column value at a time but not getting how to add multiple column values of each row to listbox
Dim dt As DataTable = Dst.Tables("user")
For Each row As DataRow In dt.Rows
lstUsers.Items.Add(row("User_Name"))
Next
Above code works perfectly but I also want to add First_name as well as last_name to the list box at the same time.
Use same approach as you have, but put all values you want in one string.
Dim dt As DataTable = Dst.Tables("user")
For Each row As DataRow In dt.Rows
Dim sItemTemp as String
sItemTemp = String.Format("{0},{1},{2}", row("User_Name"), row("First_Name"), row("Last_Name"))
lstUsers.Items.Add(sItemTemp)
Next
String.Format() function will call .ToString() on all parameters.
In this case if row(ColumnName) is NULL value then .ToString() return just empty string
You have 2 choices:
Using the ListBox:
To use the ListBox, set the font to one that is fixed width like courier new (so that the columns line up), and add the items like this:
For Each row As DataRow In dt.Rows
lstUsers.Items.Add(RPAD(row("User_Name"),16) & RPAD(row("First_Name"),16) & RPAD(row("Last_Name"),16))
Next
The RPAD function is defined like this:
Function RPAD(a As Object, LENGTH As Object) As String
Dim X As Object
X = Len(a)
If (X >= LENGTH) Then
RPAD = a : Exit Function
End If
RPAD = a & Space(LENGTH - X)
End Function
Adjust the LENGTH argument as desired in your case. Add one more for at least one space. This solution is less than ideal because you have to hard-code the column widths.
Use a DataGridView control instead of a ListBox. This is really the best option, and if you need, you can even have it behave like a ListBox by setting the option to select the full row and setting CellBorderStyle to SingleHorizontal. Define the columns in the designer, but no need to set the widths - the columns can auto-size, and I set that option in the code below. if you still prefer to set the widths, comment out the AutoSizeColumnsMode line.
The code to set up the grid and add the rows goes like this:
g.Rows.Clear() ' some of the below options are also cleared, so we set them again
g.AutoSizeColumnsMode = DataGridViewAutoSizeColumnMode.AllCells
g.CellBorderStyle = DataGridViewCellBorderStyle.SingleHorizontal
g.SelectionMode = DataGridViewSelectionMode.FullRowSelect
g.AllowUserToAddRows = False
g.AllowUserToDeleteRows = False
g.AllowUserToOrderColumns = True
For Each row As DataRow In dt.Rows
g.Rows.Add(row("User_Name"), row("First_Name"), row("Last_Name"))
Next
You might solved your problem by now but other users like me might have issue with it.
Above answers given worked for me even but I found a same answer in a simple way according to what I want..
cmd = New SqlCommand("select User_Name, First_Name, Last_Name from User")
Dim dr As SqlDataReader = cmd.ExecuteReader(YourConnectionString)
If dr.HasRows Then
Do While dr.Read
lst.Items.Add(dr.Item(0).ToString & " " & dr.Item(1).ToString & " " & dr.Item(2).ToString)
Loop
End If
This worked for me, maybe wrong way but I found it simple :)
May I suggest you use a ListView control instead of Listbox?
If you make the switch, here's a sample subroutine you could use to fill it up with the data you said you want. Adapt it the way you like; there's much room for improvement but you get the general idea:
Public Sub FillUserListView(lstUsers As ListView, Dst As DataSet)
Dim columnsWanted As List(Of String) = New List(Of String)({"User_Name", "First_Name", "Last_Name"})
Dim dt As DataTable = Dst.Tables("user")
Dim columns As Integer = 0
Dim totalColumns = 0
Dim rows As Integer = dt.Rows.Count
'Set the column titles
For Each column As DataColumn In dt.Columns
If columnsWanted.Contains(column.ColumnName) Then
lstUsers.Columns.Add(column.ColumnName)
columns = columns + 1
End If
totalColumns = totalColumns + 1
Next
Dim rowObjects(columns - 1) As ListViewItem
Dim actualColumn As Integer = 0
'Load up the rows of actual data into the ListView
For row = 0 To rows - 1
For column = 0 To totalColumns - 1
If columnsWanted.Contains(dt.Columns(column).ColumnName) Then
If actualColumn = 0 Then
rowObjects(row) = New ListViewItem()
rowObjects(row).SubItems(actualColumn).Text = dt.Rows(row).Item(actualColumn)
Else
rowObjects(row).SubItems.Add(dt.Rows(row).Item(actualColumn))
End If
lstUsers.Columns.Item(actualColumn).Width = -2 'Set auto-width
actualColumn = actualColumn + 1
End If
Next
lstUsers.Items.Add(rowObjects(row))
Next
lstUsers.View = View.Details 'Causes each item to appear on a separate line arranged in columns
End Sub