Basically i'm trying to make it so if the Selected Index from a listbox (for example lets say the selected index is "Server1") contains a number ("1") or a certain word ("Server") it would do a certain thing. For example: If the selected index from the listbox contains a number 1, it would enter 1 into a text box. If the selected index contains a number 2, it would open up a application, just for an example.
what i tried:
if (csrListBox.SelectedIndex = "1");
and:
{
List<string> items = ListBox.Items.Cast<string>().ToList();
foreach (string item in ListBox.Items)
{
Regex regex = new Regex(#"1");
Match match = regex.Match(item);
if (match.Success)
{
*Doing Something*
}
}
ListBox.DataSource = items;
}
Try this:
if (csrListBox.SelectedIndex == 1);
The second "=" sign matters - it states you're doing a boolean check instead of assigning value "1" to the value.
Mistake - You are assigning value.
Use compare operator ==. and SelectedIndex is int not string.
if (csrListBox.SelectedIndex == 1)
{
// Your code goes here.
}
I would suggest you work with ListBox item values instead of selectedIndex as the SelectedIndex can only be an integer value. Something like this linq query will return if the ListBox contains a certain value that is selected. This takes care of multi-selections too.
var myValue = "1";
bool listContainsItem = ListBox.Items.Any(item => item.Value == myValue && item.Selected);
Related
I want to display in ascendent order a list of string (numbers) that is added to a combobox. The project is in .NET 4.7.2
I have a string list of numbers such as:
{"3.453","1.123","2.024","1.567"}
and I would like that when these are displayed in my combobox they appear in order :
{,"1.123","1.567","2.024","3.453"}
The values come from reading multiple XML files and when the name == CardID is found it is added to the combobox "cb_card" items.
...
if (name == "CardID")
{
if (!mainWindow.cb_card.Items.Contains(value))
{
mainWindow.cb_card.Items.Add(value);
}
}
...
I have tried to:
Set the Combobox property Sorted = "true" but an error appears:
XLS0413 The property 'Sorted' was not found in type 'ComboBox'.
I tried to add the values to a list, then sort the list and finally add them to the combobox. I edited the code shown above:
...
List<string> sortedCardId = new List<string>();
if (name == "CardID")
{
if (!mainWindow.cb_card.Items.Contains(value))
{
sortedCardId.Add();
}
}
sortedCardId.Sort();
foreach (string ID in sortedCardId)
{
mainWindow.cb_card.Items.Add(ID);
}
...
but the order stayed the same as when it is nor ordered.
I tried some variants of this last code, by converting the string list in doubled, sort it and reconvert it ot string, but I got to many errors qhich I couldn't debugg with my current knowledge.
I tried to add the values to an array instad of a list, sort the array and add the values, but then the combobox appeared empty.
thanks a lot for your time and help in advance .
You can use List.Sort for this. If you are sure that the list contains only numeric values that can be parsed as a decimal (or double, ...), you can use a custom sort comparison that converts the strings to a decimal before comparing them:
var lst = new List<string>() {"3.453","1.123","2.024","1.567"};
lst.Sort((string a, string b) => (int)(decimal.Parse(a) - decimal.Parse(b)));
// This writes the list content as "1.123, 2.024, 1.567, 3.453"
Console.WriteLine(string.Join(", ", lst));
When comparing two items, the comparison returns
less than 0: a is smaller than b
0: a == b
greater than 0: a is bigger than b
This is why subtracting b from a leads to a correct result of the comparison.
In my program I have a tabItem that gets selected when a TreeViewItem with an equivalent header is selected.
This is what I currently have (It works):
(parent_TreeViewItem.Items.Contains(SelectedItem))
{
tabControl1.SelectedItem = tabControl1.Items //Changes tab according to TreeView
.OfType<TabItem>().SingleOrDefault(n => n.Header.ToString() == SelectedItem.Header.ToString());
}
The difference with what I'm doing this time is that the tabItem's header that I'm selecting is composed of a string and an integer.
For example: The TreeViewItem selected will always have a header named "Arrival", but the tabItem's header will have a form like "Arrival" + integer. The integer value will come from the parent node's header.
For this process I'm thinking that I'll first need to get the header value of the parent node, since it contains that integer value I need. Then I'll need to modify my code above in someway to query for a node with a header like, "Arrival" + parentHeader.
How would I do something like this?
Thank you.
UPDATE
My current code, using #varocarbas's answer. I am using the first version of the answer that involved setting the integer curNumber to the value of the parent's header. The code compiles but does not do anything when the "Arrival" node is clicked on.
if (parent_TreeViewItem.Items.Contains(SelectedItem.Parent)) //Location - Actions tabs
{
TreeViewItem parentItem = (TreeViewItem)SelectedItem.Parent;
int curNumber = getNumber(parentItem.Header.ToString());
tabControl1.SelectedItem = tabControl1.Items //Changes tab according to TreeView
.OfType<TabItem>().SingleOrDefault(n => n.Header.ToString() == SelectedItem.Header.ToString() + curNumber.ToString());
}
public static int getNumber(string parentNodeHeader)
{
int curNumber = 0;
curNumber = Convert.ToInt32(parentNodeHeader);
return curNumber;
}
UPDATE 2: Because the "Arrival" node is the grandchild of the node I was using as a parent I have changed the if statement in my first line to:
if (parent_TreeViewItem.Items.Contains(SelectedItem.Parent))
Firstly, you have to get the parent node and the number contained in its header:
TreeViewItem parentItem = (TreeViewItem)selectedItem.Parent;
int curNumber = getNumber(parentItem.Header.ToString());
getNumber is a function to retrieve the number from its exact location in the parent node header. You have to tell more about that in order to write a proper function; for the time being, just the basics (it extracts all the numbers in the input string):
private int getNumber(string parentNodeHeader)
{
int curNumber = 0;
//Required string-analysis actions
//Sample functionality: extract all the numbers in the given string
string outString = "";
int count = -1;
do
{
count = count + 1;
Char curChar = Convert.ToChar(parentNodeHeader.Substring(count, 1));
if (Char.IsNumber(curChar))
{
outString = outString + parentNodeHeader.Substring(count, 1);
}
} while (count < parentNodeHeader.Length - 1);
if (outString != "")
{
curNumber = Convert.ToInt32(outString);
}
return curNumber;
}
And then you have to update the query to account for the new information:
.OfType<TabItem>().SingleOrDefault(n => n.Header.ToString() == selectedItem.Header.ToString() + curNumber.ToString());
UPDATE
The function above just shows the kind of code I usually rely on; but for simple situations (like the proposed one of getting all the numbers in a string), you might prefer to rely on Regex, as suggested by Viv. You might rely on something on the lines of:
private int getNumber(string parentNodeHeader)
{
System.Text.RegularExpressions.Match m = System.Text.RegularExpressions.Regex.Match(parentNodeHeader, #"\d+");
return Convert.ToInt32(m.Value);
}
This function only delivers the first set of consecutive numbers it finds; different result than the function above but enough as a proof of concept (intention of this answer).
How would I go about about replacing the text of blank items in column 5 of my listView with the word "No"?
I tried this but it threw an InvalidArgument=Value of '4' is not valid for 'index'. error:
foreach (ListViewItem i in listView1.Items)
{
if (i.SubItems[4].Text == " ")
{
i.SubItems[4].Text = i.SubItems[4].Text.Replace(" ", "No");
}
}
The code provided above will get all items within ListView1.Items and check if the sub-item of index 4 and its property Text is equal to which may result in the described error if the index exceeds the array limit. You may avoid this by making sure that this item is not Nothing.
Example
foreach (ListViewItem i in listView1.Items) //Get all items in listView1.Items
{
if (i.SubItems.Count > 3) //Continue if i.SubItems.Count is more than 3 (The array contains i.SubItems[3] which refers to an item within the 4th column (i.SubItems.Count is not an array. Therefore, it'll start with 1 instead of 0))
{
if (i.SubItems[3].Text == " ") //Continue if i.SubItems[3].Text is equal to
{
i.SubItems[3].Text = i.SubItems[3].Text.Replace(" ", "No"); //Replace with No
}
}
}
Notice: Arrays are zero-indexed which means that they start with 0 instead of 1.
Notice: If you only have 4 columns, i.SubItems.Count would be 4 and not 3 because it's a normal int considering that all columns are filled.
Thanks,
I hope you find this helpful :)
If I were you, I'd Use the debugger to figure out what's actually going on.
You can check and see what's actually in i.SubItems, and make sure it's actually what you think it is.
The only possible thing i can think of is maybe you made a typo somewhere or that i.SubItems[4] actually just isn't valid.
maybe you're iterating through some of your list items, but not all of your list items have 5 columns, or maybe some are empty.
Once you get that first error figured out, your logic for replacing the text might work better like this:
if (i.SubItems != null && string.IsNullOrEmpty(i.SubItems[4].Text))
{
i.SubItems[4].Text = "No";
}
I have a large string that contains text:
"value 1
value 2
value 3
etc..." //over 100 values
I am trying to create a listbox with it's items based on the values in this string.
I used a try catch as I was getting an argument out of range exception which stopped the error but I can't see any items in the listbox :P
string value = "";
int currentIndexPos = 0;
foreach (System.Text.RegularExpressions.Match m in System.Text.RegularExpressions.Regex.Matches(listStr, "\r\n?"))
{
try
{
value = formatted.Substring(currentIndexPos, m.Index - 1); // -1 so the matched value isn't used.
listBox1.Items.Add(value);
currentIndexPos = m.Index + 1;
}
catch
{
//argument out of range exception
//Index and length must refer to a location within the string. Parameter name: length
}
}
As many have said, just use String.Split. However, there's no need for a foreach loop or resorting to LINQ, just do this:
listBox1.Items.AddRange(String.Split(...));
Try something like this
var values = listStr.Split("\r\n".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
foreach(string value in values)
{
listBox1.Items.Add(value);
}
Since you are in essence doing a split why not use that function and ignore the index operations.
var lst = String.Split("\r".ToCharArray(),"listStr");
lst.select((x)=>listBox1.Items.Add(x));
How can I check that a combobox in winforms contains some value?
Is there any way of doing it without iterating through all items?
if (comboBox1.Items.Contains("some value"))
{
}
If the items are some custom object instead of strings you might need to override the Equals method.
int index = comboBox1.FindString("some value");
comboBox1.SelectedIndex = index;
http://msdn.microsoft.com/en-us/library/wxyt1t12.aspx#Y500
There's also FindStringExact http://msdn.microsoft.com/en-us/library/c440x2eb.aspx
The other answers didn't work for me.
This did:
if (comboBox1.Items.Cast<string>().Any(i => i == position))
{
// Items contains value
}
Hope this helps!
To find exact data from combo box we have to check with FindStringExact
int resultIndex = cbEmployee1.FindStringExact(item.Text);
Using the accepted answer did not work for me as it always returned false even though a check of the list show the value present. What I use is the FindStringExact method, as recommend by Louis and Amit. In this case its a value entered in the comboBox text box.
var index = comboBox1.FindStringExact(comboBox1.Text)
if(index > -1)
{
//Success followup code
}