VB.net Listview select - vb.net

I am having problems with highlighting the found listview item using the code below:
If lstMaster.View = View.Details AndAlso lstMaster.Items.Count > 0 Then
Dim lvi As ListViewItem = lstMaster.FindItemWithText(txtSearchSR.Text, True, 0)
If lvi IsNot Nothing Then
MsgBox("found")
lvi.ListView.Items(0).Selected = True 'Does not seem to work...
End If
End If
How do i highliht the found column?
David

Try setting Subitems
lvi.Items[0].UseItemStyleForSubItems = false
lvi.Items[0].SubItems[0].BackColor = Color.Black
lvi.Items[0].SubItems[0].ForeColor = Color.White
if that doesn't work try
lvi.UseItemStyleForSubItems = false
lvi.SubItems.Add(new ListViewItem.ListViewSubItem(lvi,"subitem", Color.Black, Color.White, lvi.Font ))

You need
lvi.Selected = True
From your snippet,
lvi.ListView.Items(0) will always return the first ListViewItem in the listview.

Got it! :o)
lstMaster.Items(lvi.Index).Selected = True
lstMaster.Select()
lstMaster.SelectedItems.Item(0).EnsureVisible()

Related

Datagridview image column moves on update

On my form i got datagridview which is populating by some data. There is also a combobx on this form and when selection change has happend then based on selected value - datagridview datasource is set to be nothing and then filled up again. Everything was working well until i decided to add additional datagridview image column which i placed on the end of grid and to show images based on text from some previous column text data. Unfortunetly i have problem with displaying images itself (red marks) and biggest problem is when i change combobox selection my additional datagrid image column is moving 1 position to left everytime combo is changed. I've spent whole day looking for issue but can't find any answer on that. I thought maybe that's because grid datasource is not being cleaned (nothing) but it is. Can you please help me out what could be a problem here? Below find my code and screenshoots of problem. Hope you help me to fix it as i am really stackoverflowed.
My Form Load event - that's where i load combobox:
Private Sub FrmTransportView_Load(sender As Object, e As EventArgs) Handles MyBase.Load
RemoveHandler CboProjects.SelectedIndexChanged, AddressOf CboProjects_SelectedIndexChanged
Try
mydb.OpenConn()
If mydb.conn.State = ConnectionState.Open Then
Form.InitCombo(CboProjects, "SELECT * from tbProjekt", mydb.conn, "Nazwa", "Id")
mydb.CloseConn()
'ChangeControlsLanguage()
Trans = New Transport
Trans.ProjectId = CboProjects.SelectedValue
RefreshGridAfterProjectIdChanged()
AddHandler CboProjects.SelectedIndexChanged, AddressOf CboProjects_SelectedIndexChanged
End Try
End Sub
PopulateGrid method:
Public Sub PopulateGrid()
Try
If IsNothing(Trans.ListByProjectId_checkifanyrows()) Then
Me.BeginInvoke(New MethodInvoker(AddressOf Me.Close))
Else
Else
dgvTransport.DataSource = Nothing 'Clean datagrid before new data
dgvTransport.Refresh()
dgvTransport.DataSource = Trans.ListByProjectId()
AlignGrid()
PlaceImages()
End If
End Try
End Sub
Align method - placed within PopulateGrid method as you see when dgvTransport as set to nohing and then its detasource set to new data: Trans.ListByProjectId() now i am aligning it - hiding some columns etc... As you can see also i am adding this new image column... :
Private Sub AlignGrid()
Try
dgvTransport.Columns(0).Visible = False 'Project id
dgvTransport.Columns(1).Visible = False 'Id
dgvTransport.Columns(2).Visible = True 'Lp
dgvTransport.Columns(3).Visible = True 'Status
dgvTransport.Columns(4).Visible = True 'Dataprzyjazdu
dgvTransport.Columns(5).Visible = True 'DataRozpoczeciaZaladunku
dgvTransport.Columns(6).Visible = True 'DataOdjazdu
dgvTransport.Columns(7).Visible = True 'TypTransportu dgvTransport.Columns(8).Visible = False 'TypKontenera (reprezentacja liczbowa z tabeli tbTransport)
dgvTransport.Columns(9).Visible = True 'NumerKontenera
dgvTransport.Columns(10).Visible = True 'NumerCiezarowki
dgvTransport.Columns(11).Visible = True 'Plomba
dgvTransport.Columns(12).Visible = False 'Kierowca
dgvTransport.Columns(13).Visible = False 'Opis
dgvTransport.Columns(14).Visible = False 'Nazwa (nazwa projektu)
dgvTransport.Columns(15).Visible = True 'TypKontenera (reprezentacja za pomoca nazwy ze zlaczenia INNER JOIN))
Dim img As DataGridViewImageColumn = New DataGridViewImageColumn()
img.HeaderText = "Status2"
img.Name = "Status2"
dgvTransport.Columns.Insert(16, img)
'potrzebny aby zadzialalo: DgvMach.ColumnHeadersDefaultCellStyle.BackColor = Color.Gold
dgvTransport.EnableHeadersVisualStyles = False
'headers look
With dgvTransport.ColumnHeadersDefaultCellStyle
'The way to do this is to set the EnableHeadersVisualStyles flag for the data grid view to False, and set the background colour via the ColumnHeadersDefaultCellStyle.BackColor property. For example, to set the background colour to blue, use the following (or set in the designer if you prefer):
'If you do not set the EnableHeadersVisualStyles flag to False, then the changes you make to the style of the header will not take effect, as the grid will use the style from the current users default theme. The MSDN documentation for this property is here.
.BackColor = Color.White
.ForeColor = Color.Black
.Font = New Font("Ariel", 10, FontStyle.Regular)
.Alignment = DataGridViewContentAlignment.MiddleCenter
End With
dgvTransport.AllowUserToAddRows = False
dgvTransport.[ReadOnly] = True
dgvTransport.MultiSelect = False
dgvTransport.SelectionMode = DataGridViewSelectionMode.FullRowSelect 'zaznacza caly wiersz po kliknieciu
dgvTransport.AutoSizeColumnsMode = DataGridViewAutoSizeColumnMode.Fill 'WAZNE!!!: RESIZUJE CALY CONTENT GRIDA NIE ZOSSTAWIAJAC CIEMNEGO TLA !!!
dgvTransport.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.AllCells
With dgvTransport.DefaultCellStyle
.BackColor = Color.White
.ForeColor = Color.Black
.Font = New Font("Ariel", 9, FontStyle.Regular)
.Alignment = DataGridViewContentAlignment.MiddleCenter
End With
'This will disable row autosizing and manual row resizing. To set the row height you can use the Height and MinimumHeight properties of the RowTemplate.
dgvTransport.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.None
dgvTransport.AllowUserToResizeRows = False
End Sub
FrmTransportView_Shown event:
Private Sub FrmTransportView_Shown(sender As Object, e As EventArgs) Handles MyBase.Shown
AddHandler dgvTransport.SelectionChanged, AddressOf dgvTransport_SelectionChanged
End Sub
RefreshGridAfterProjectIdChanged
Public Sub RefreshGridAfterProjectIdChanged()
Trans.ProjectId = CboProjects.SelectedValue
PopulateGrid()
End Sub
CboProjects_SelectedIndexChanged
Private Sub CboProjects_SelectedIndexChanged(sender As Object, e As EventArgs) Handles CboProjects.SelectedIndexChanged
RefreshGridAfterProjectIdChanged()
End Sub
PlaceImages
Private Sub PlaceImages()
For i As Integer = 0 To dgvTransport.Rows.Count - 1
Dim sHeader As String = dgvTransport.Columns(16).Name
If sHeader = "Status2" Then
Dim LINK = dgvTransport.Rows(i).Cells(8).Value
If LINK.ToString.Contains("1") Then
Dim Img As New DataGridViewImageCell
Img.Value = My.Resources._1
dgvTransport.Rows(i).Cells(16).Value = Img.Value
End If
If LINK.ToString.Contains("2") Then
Dim Img As New DataGridViewImageCell
Img.Value = My.Resources._2
dgvTransport.Rows(i).Cells(16).Value = Img.Value
End If
If LINK.ToString.Contains("3") Then
Dim Img As New DataGridViewImageCell
Img.Value = My.Resources._3
dgvTransport.Rows(i).Cells(16).Value = Img.Value
End If
End If
Next
End Sub
That's how it looks for first form load: (strange thing is column index of image column (Status2) is 0 - should be 16 as i placed index for that column to 16 in Align method.. As you see also not images are showing up...
Now when i am going to change selection in combobox:
of course as you can note from code this method handler is called: CboProjects_SelectedIndexChanged
so then again grid datasource will be set to Nothing, populate again, then align gird..
and that's what is shown after: (see indexes - also some image show up and column "Status2" was moved to left..)
3rd combobox change etc...
Hope to find someone here to help me out as i really have no idea how to fix that. Hope everything is clear.
Sorry this is coming a little late. Just a suggestion - I didn't experiment with it. Try to insert the DataGridImageColumn first before editing the visibility of the other columns.
Not too related, but in your AlignGrid sub, the static properties like ".BackColor" can be set on design just to reduce code.
Let us know your observations.
Thanks

Check all checkboxes in a listview

I want to have a button that will check all checkboxes in my listview. I have:
Dim I as Integer
If listViewAccounts.CheckedItems.Count > 0 then
(>>My Problem here<<)
End if
What to do next?
for i = 0 to listViewAccounts.Items.Count -1
listViewAccounts.Items(i).Checked = true
next
Or just use Linq
listView1.Items.OfType(Of ListViewItem).All(Function(c)
c.Checked = True
Return True
End Function)
I used:
For Each lvi As ListViewItem In listViewAccounts.Items
lvi.Checked = True
Next

Select only 1 item from Listview

I have some code that reads the value of a Listview on a button click. However, what it does is select all the entries to add to another Listview. How do I adjust my code to allow for single items selection. Thanks
lvSelectRequestItems.Items.Clear()
While dr.Read()
Dim LVS As New ListViewItem
'LVS.SubItems.Clear()
With (LVS)
.UseItemStyleForSubItems = False
.Text = dr("Box").ToString()
.SubItems.Add(dr("CustRef").ToString())
End With
lvSelectedItems.Items.Add(LVS)
End While
If ListViewObj.SelectedItems.Count >= 1 Then
While ListViewObj.SelectedItems.Count >= 1
ListViewObj.SelectedItems(0).Selected = False
End While
ListViewObj.Items(ListViewObj.FocusedItem.Index).Selected = True
End If

Width of drawn list box?

I've created a custom combobox that uses a custom instance of a listbox control as the dropdown menu.
In order to customize the selection highlight of the listbox, I had to change its 'DrawMode' property to 'OwnerDrawFixed' and added the following code:
Private Sub _listBox_DrawItem(sender As Object, e As DrawItemEventArgs)
If e.Index >= 0 Then
e.DrawBackground()
If (e.State And DrawItemState.Selected) = DrawItemState.Selected Then
Using br = New LinearGradientBrush(e.Bounds, ColorSelectionListbox, ColorSelectionListbox, 0)
e.Graphics.FillRectangle(br, e.Bounds)
End Using
End If
Using b As New SolidBrush(ColorTextListbox)
e.Graphics.DrawString(_listBox.GetItemText(_listBox.Items(e.Index)), e.Font, b, e.Bounds)
End Using
e.DrawFocusRectangle()
RaiseEvent DrawItem(Me, e)
End If
End Sub
But with this, the width that I set for it is ignored and becomes a fixed width of 15 or so pixels.
How can I set the width of the owner-drawn control? Currently I have it as a property:
Public Property DropDownWidth() As Integer
Get
Return _dropDownWidth
End Get
Set(value As Integer)
_dropDownWidth = value
_listBox.Width = value
Invalidate(True)
End Set
End Property
Below is the rest of the code that is relevant, but nevermind.. I fixed the issue by setting the Autosize property of _controlHost to False. I had it set to True in order to display all items within the list (without having to define a dropdown maximum) but for some reason it behaves differently when the DrawMode is set to OwnerDraw.
_listBox = New ListBox()
_listBox.IntegralHeight = True
_listBox.BorderStyle = BorderStyle.FixedSingle
_listBox.SelectionMode = SelectionMode.One
_listBox.BindingContext = New BindingContext()
_dropDownWidth = Me.Width
_listBox.Width = _dropDownWidth
_controlHost = New ToolStripControlHost(_listBox)
_controlHost.Padding = New Padding(0)
_controlHost.Margin = New Padding(0)
_controlHost.AutoSize = False 'Used to be variable property _dropDownAutoSize
_popupControl = New ToolStripDropDown()
_popupControl.Padding = New Padding(0)
_popupControl.Margin = New Padding(0)
_popupControl.AutoSize = True '
_popupControl.DropShadowEnabled = False
_popupControl.Items.Add(_controlHost)

simple text color in rich text box

I can find a million examples of doing reg ex to apply syntax highlighting to a rich text box. but what i need it just a simple way to add in a word of a diffrent color.
What would the code be to just put the words "Hello World" into a textbox and have Hello be red and World be green?
This code doesnt work.
this.richTextBox1.SelectionColor = Color.Red
this.richTextBox1.text += "Test"
This code adds text "Hello" in red color and "World" in green to the RichTextBox.
RichTextBox1.SelectionColor = Color.Red
RichTextBox1.SelectedText = "Hello "
RichTextBox1.SelectionColor = Color.Green
RichTextBox1.SelectedText = "World"
Select the text after you put it in and then change the color.
For example:
richTextBox1.Text += "Test"
richTextBox1.Select(richTextBox1.TextLength - 4, 4)
richTextBox1.SelectionColor = Color.Red
Ive worked with it in VB6 and i think its the same:
You must select the text and then apply
this.richTextBox1.SelectionColor = Color.Red
The added text always appears in the defaut color, you must select it and then change its color:
this.richTextBox1.text="Hello world!"
this.richTextBox1.selstart=0
this.richTextBox1.sellength=5
this.richTextBox1.SelectionColor = Color.Red
As i dont use vb.net, you must check the spelling but i think thats the key.
The code i wrote is supposed to print "Hello" in red and "World!" in black.
Try this
RichTextBox2.SelectionLength = 0
RichTextBox1.SelectionStart = 0
' We deselect everything first in case the user has something selected.
RichTextBox1.SelectionColor = Color.Red
RichTextBox1.SelectedText = "Hello "
RichTextBox1.SelectionColor = Color.Green
RichTextBox1.SelectedText = "World "
This will add it to the start of the textbox. I think you could also make SelectionStart = RichTextBox1.TextLength which would put it at the end instead of the start.
The code doesn't work:
this.richTextBox1.SelectionColor = Color.Red
this.richTextBox1.text += "Test"
Change the second line to this:
this.richTextBox1.SelectionColor = Color.Red
this.richTextBox1.selectedtext = "Test"
Try this
Sub colorWord(ByVal word As String, ByVal color As Color) ' by im4dbr0
For i As Integer = 0 To RichTextBox1.TextLength
Try
If RichTextBox1.Text.ElementAt(i).ToString = word.ElementAt(0).ToString Then
Dim found As Boolean = False
For j As Integer = 1 To word.Count - 1
If RichTextBox1.Text.ElementAt(i + j) = word.ElementAt(j) Then
found = True
Else
found = False
Exit For
End If
Next
If found = True Then
RichTextBox1.Select(i, word.Length)
RichTextBox1.SelectionColor = color
End If
End If
Catch ex As Exception
Continue For
End Try
Next
For multiple words use loop
Dim Words As New List(Of String)
Words.Add("Its")
Words.Add("That")
Words.Add("Simple")
For i As Integer = 0 To Words.Count - 1
colorWord(Words.Item(i), Color.Red)
Next