Double-Clicking Item in ListView - c#

So I added a list view, and I am displaying 3 columns of strings in each. I also have the full row select on. I want to be able to double click on one of the rows, and have it return the string in the 3rd column. I've tried to look everywhere for a solution to this, but so far nothing comes up.
My code so far is:
private void listView_MouseDoubleClick(object sender, MouseEventArgs e)
{
MessageBox.Show(songList.SelectedItems[2].ToString());
}
Yet it returns an error saying "InvalidArgument=Value of '2' is not valid for 'index'.
Parameter name: index"

You could try:
if (songList.SelectedItems.Count > 0)
{
ListViewItem item = songList.SelectedItems[0];
string s_you_want = item.SubItems[1].Text;
}
Taken a ListViewItem, you can take columns values using SubItems[] property.

I think that you hould bound not your listView to doubleClick event, but listViewItem. sender will have DataContext, from which you can get your third column.

How do you fill the ListView? Wihtout knowing this, it's difficult to help. May be you could try this:
Set a breakpoint in this line:
MessageBox.Show(songList.SelectedItems[2].ToString());
As soon as the debugger hits the breakpoint you could select songList and hit Shift-F9.
Now you can explore the songList and check yourself how to get the string of the third column.

SelectedItems returns a SelectedListViewItemCollection and with the indexer you are accessing elements in this collection, i.e. ListViewItems, not the columns. this means that if you have a single row selected the collection contains only one item, and trying to access the third one gives you the error.
Try (edit according to Marco's comment):
songList.SelectedItems[0].SubItems[1].Text

Related

Need help in a school programming internal

I have two lists called standards and credits. The standards list is added to a ComboBox. When I click an item in the ComboBox I want to be able to show an item in the credits list. For example I click first index in the ComboBox, I want to show item in the first item of the credits list. I have this code but it gives me an error I can't fix it. This is the error im getting:
System.ArgumentOutOfRangeException
It's from this line of code
lblCredits.Text = credits.ElementAt(standard.IndexOf(cboStandard1.Text))
-
private void cboStandard1_SelectedIndexChanged(object sender, EventArgs e)
{
if (cboStandard1.SelectedIndex + 1 > 0)
{
lblCredits.Text = credits.ElementAt(standard.IndexOf(cboStandard1.Text));
}
}
This is showing that my lists are the same length
private void standardlist()
{
standard.Add("91632");
standard.Add("91633");
standard.Add("91634");
standard.Add("91635");
cboStandard1.DataSource = standard;
((ComboBox)cboStandard1).SelectedIndex = -1;
credits.Add("4");
credits.Add("6");
credits.Add("4");
credits.Add("4");
}
Like I said, binding the ComboBox, i.e. setting its DataSource property, will select the first item by default, which will raise the SelectedIndexChanged event, which will execute your code. That all happens before you've populated the credits list, which is why it contains no items. There are two things you can do, and you may choose to do both:
Populate the credits list before setting the DataSource of the ComboBox.
Handle the SelectionChangeCommitted event instead of SelectedIndexChanged.
The SelectionChangeCommitted event is raised only when the user selects an item via the UI, so it will not be raised when you bind the data and then reset the SelectedIndex, while SelectedIndexChanged will be raised twice. Even if you do implement option 1, you'll still have an issue on the second SelectedIndexChanged event because you'll be passing -1 to ElementAt, so you'll get an ArgumentOutOfRangeException thrown.

DropDownList Showing First Item Empty

Every time this Dropdown is showing first Item Blank
ComboBox cb;
List<string> namesCollection=new List<string>();
namesCollection.Add("---- Select ----");
namesCollection.Add("ABC1");
namesCollection.Add("ABC2");
namesCollection.Add("ABC3");
namesCollection.Add("ABC4");
foreach(string pname in namesCollection)
cb.Items.Add(pname);
Does anyone have solution for this ?
You appear to be defining the ComboBox right there in your code, so I'll assume it's actually displayed somewhere in your form / window.
It's normal for the ComboBox to display a blank line initially.
Specify the item you want to display, immediately after populating the ComboBox with data:
cb.SelectedIndex = 0;
You probably have a line feed in your items collection. Hard to see. Adding a cb.Items.Clear() before populating is probably a good idea anyway and will get rid of the problem, if you can't locate it.

ComboBox doubling in values c#

I have following piece of code:
private void nameTextBox_Leave(object sender, EventArgs e)
{
var names = ConfigurationManager.AppSettings.AllKeys
.Where(k => k.StartsWith("name"))
.ToArray();
// Add names to combobox
comboBox.Items.AddRange(names);
}
Problem is each time I press Tab from textbox, comboBox elements keep on doubling. If it had Ken, John, Tim in there, it will show that twice if I press tab again.
I tried using distinct in the names above but that does not do anything as new instantance is created each time and previous is saved. I cannot make comboBox empty right after adding names as it is being used in a button click latter on in the code.
Only alternative i thought was of declaring a global variable and make sure its value is 0
and then only insert values in comboBox, and change it to 1 once value is inserted. But that does not seem like a good coding practice.
Is there any better way to get this done?
Add comboBox.Items.Clear() before the AddRange. So the whole block should be.
private void nameTextBox_Leave(object sender, EventArgs e)
{
var names = ConfigurationManager.AppSettings.AllKeys
.Where(k => k.StartsWith("name"))
.ToArray();
// Add names to combobox
comboBox.Items.Clear();
comboBox.Items.AddRange(names);
}
i'm not sure if I understand perfectly, but why can't you just clear the items before populating?
comboBox.Items.Clear()
comboBox.Items.AddRange(names);
also you could try not to use Items, but DataSource:
comboBox.DataSource = names;
The suggestions to clear the combo box first should solve your problem, but if you are loading the combo box on page load as well then I don't think this is the best solution (just masking the real problem). If you are populating the combobox on page load then add a Page.IsPostBack check in there:
example:
if(!Page.IsPostBack)
{
//Populate the initial values into the combobox
}
If you aren't then the clear solution should be fine.

Problems with selected indices in listview

I have an arraylist which contain objects of my own class. I want to fetch the object from the array list which has the index = selectedindex of listview.
I tried this :
TrackInformation t=(TrackInformation) SongList[listView1.SelectedIndices[0]];
TrackInformation is my class and SongList is an ArrayList of type TrackInformation.
listview1 does not allow multiple indices selection so I want the first element of the SelectedIndices collection.
I am getting ArgumentOutOfRangeException and it says value of '0' is not valid for 'index'.
Put this line before your code -
if(listView1.SelectedIndices.Count > 0)
{
TrackInformation t=(TrackInformation) SongList[listView1.SelectedIndices[0]];
}
The ListView.SelectedIndexChanged event has a quirk that bombs your code. When you start your program, no item is selected. Click an item and SelectedIndexChanged fires, no problem. Now click another item and the event fires twice. First to let you know, unhelpfully, that the first item is unselected. Then again to tell you that the new item is selected. That first event is going to make you index an empty array, kaboom. RV1987's snippet prevents this.
The error is because listView1.SelectedIndices is empty, do you have a row selected?
you probable want to wrap in a test
ListView.SelectedIndexCollection selected=listView1.SelectedIndicies;
if (selected.Count==0) {
// code for no items selected
} else {
TrackInformation t=(TrackInformation) SongList[selected[0]];
// rest of code to deal with t
}

How to deleselect / blank a databound ComboBox? SelectedIndex = -1 does not work

I am trying to deselect (blank out) a number of combo-boxes in my windows forms application. In my application I have a Reset method that sets the SelectedIndex for each combo to -1. All of my combo-boxes are databound, i.e. each combo-box is populated using a datasource.
I have noticed that sometimes my Reset method works, i.e. it deselects the currently selected item and blanks the combo. However, other times it chooses the first item (SelectedIndex = 0) straight after I attempt to set it to -1. From a users point of view this looks like a bug as it doesn't always "clear" the form.
According to MSDN:
"To deselect the currently selected item, set the SelectedIndex to -1. You cannot set the SelectedIndex of a ComboBox item to -1 if the item is a data-bound item."
Does anyone know of a work around?
Many thanks
Use combination of the void and property
comboBox.ResetText();
//to reset selected value
comboBox.SelectedIndex = -1;
Don't know if anyone is still interested in this, seeing as it's now 5 years later, but I found a very easy workaround. Totally non-intuitive (I only found it by looking at the reference source code), but trivial to implement:
ComboBox1.FormattingEnabled = True;
Yep, that's all there is to it!
If you're curious, you can peruse the source code to see what's going on. It appears that the root cause of the bug noted by #CuppM is the attempt to set the position in the data source:
if (!FormattingEnabled || SelectedIndex != -1) {
this.DataManager.Position = this.SelectedIndex;
}
I would guess that it should have simply been '&&' instead of '||' in the condition, as the code probably shouldn't be setting the Position to an invalid value regardless of the FormattingEnabled property.
In any case, it allows for a simple workaround. And since the default behavior if the 'Format' property is blank is a no-op, you don't have to change anything else. It just works. :-)
(I should note that I have only tried this with .NET 4.7, so I can't say whether it works for prior versions of the .NET Framework.)
You can try to set the Selected Value or Item to null (Nothing in VB)
I cant remember the behavior of throwing an exception. However, I do remember that I used to insert a value called -1, (None) to the combo-box after it was databounded usually through the databind events. I'd recommend get the data in a List and insert the new value to this list. Bind the combo to the List now.
Only the following code works for me, so try:
comboBox.ResetText(); //framework 4.0
ComboBox1.SelectedItem = null;
For anyone still looking at this old post I wanted to add a note from what Hisham answer.
Make sure to clear your list after inserting his code.
comboBox.ResetText();
//to reset selected value
comboBox.SelectedIndex = -1;
comboBox.Items.Clear();
Try assigning null or String.Empty to the SelectedValue property.
If your target framework is 4.0 - here is the solution:
Install .Net Framework 4.5 (do not change target framework of your project, just install the framework).
After installing, that line deselects databound combobox:
combobox.SelectedValue = 0;
My value member is "Id" int primary key auto-increment, so that field does not contain value 0.
However, that won't work on Windows versions, that do not support .net45
Try to set the [ComboBoxObj].SelectedIndex=-1; which will make it to empty value.
-1 refers to deselect or nullify the value of combobox
Thanks
I have had this problem for a while, but if you use:
'ComboBox.ResetText();'
it will make the text "" and leave the items in the combo box unaffected.
i used the following code in my application
private void UpdateComboBox(ComboBox Box, string Group, List<string> Numbers)
{
Box.Items.Clear();
Box.BeginUpdate();
Box.Items.Add("<<Add Contact>>");
foreach (string item in Numbers)
{
if(item != "")
Box.Items.Add(item);
}
Box.EndUpdate();
Box.ResetText();
}
So i run the method last, once all items are in the combo Box.
Try this line of code:
combobox1.Items.clear();
It works for me.
Add to your combobox one empty item, something like this:
cb.Items.Add("");
After this you can deselect your combobox by selecting the last cb item:
cb.SelectedIndex = cb.Items.Count - 1;
There you go!
You'll have the last place empty in your combobox, but it wont bother you. will it? :-)
I got the following error:
There is no row at position 0
when I was setting ComboBox.SelectedItem to -1.
Replacing by ComboBox.ResetText() worked OK. This was using .Net 4.6.1, with VS 2013 where TextFormatting = True by default for ComboBoxes.
you may try to use this solution..
dataGrid.DataSource = Nothing
dataGrid.DataBind()
hope its help!..:D

Categories

Resources