I can't programmatically select an item on a listview in c# 2005 beta2. Basically, I:
1. Create a Listview called Listview1
2. Populate Listview1 with some preset items during startup of form
3. Select first item by:
Listview1.Items[0].Selected = true;
4. Problem is that I get zero when I execute:
Listview1.SelectedItems.Count
I have tried setting focus to Listview1 but I still set zero returned. Is this a bug - or am I doing something wrong
Thanks

Programmatically select a Listview item
Ana Aguaisa
It isn't a terribly good guess, I'd expect you have problems in VB.NET as well as C# if it was something like this.
The following simple test case seems to do what one would expect so there must be some wrinkle in your program we aren't seeing
Create a simple form program and drop a a ListView and two Buttons on the form. Use the designer to add one column to the ListView.
The first button's click handler fills the list view
private void button1_Click(object sender, System.EventArgs e)
{
ListViewItem item1 = new ListViewItem("item1");
listView1.Items.Add (item1);
ListViewItem item2 =
new ListViewItem("item2");listView1.Items.Add (item2);
ListViewItem item3 =
new ListViewItem("item3");listView1.Items.Add (item3);
}
The second button programmatically selects the first item in the list
private void button2_Click(object sender, System.EventArgs e)
{
listView1.Items[0].Selected = true;
int i = GetSelectedIndex (listView1);
Console.WriteLine ("Select: i={0}", i);
} public static int GetSelectedIndex(ListView InListView)
{
if (InListView.SelectedItems.Count == 0)
{
return 0;
}
// Too lazy to dial out the index
return InListView.SelectedItems.Count;
}
DanKline
Not sure if posting all the code will help because it is very long ... below are parts of it. Program is a free song projection software which I have written in VB.NET. I am in the process of porting it to c#:
//Calling Procedure
//WorshipList is the ListView which has just been populated with data from a text file
if (WorshipList.Items.Count > 0)
{
WorshipList.Items[0].Selected = true;
WorshipListIndexChanged(1);
}
private void WorshipListIndexChanged(int StartingSlide)
{
int Selecteditem;
gf.PreviewItem.Source = gf.ItemSource.WorshipList;
gf.TotalWorshipListItems = WorshipList.Items.Count;
Selecteditem = gf.GetSelectedIndex(WorshipList);
if (Selecteditem >= 0)
{
...
}
public static int GetSelectedIndex(ListView InListView)
{
if (InListView.SelectedItems.Count == 0)
{
...
}
}
//The above: InListView.SelectedItems.Count returns 0
OpticalMan
Try this...
lvTheList.SelectedIndex = iIndexToSelect; //e.g 0 for the first item etc
Hope this helps,
Gary
Greg Davis
I have got round the problem by looping through each item on the listview and check if its selected value is true.
Proxymo