I have listview with 3 items and 1 subitems
So I would like to check if a row on item[3] is String.Empty.
if items[3] is empty it will not pass my items[3] to label1.Text.
if items[3] is not empty it will pass my items[3] to my label1.Text
.
this is my code
if (listView1.Items[3].SubItems[1].Text == string.Empty)
{
label1.Text = "";
}
else
{
label1.Text = listView1.Items[3].SubItems[1].Text;
}
when my 3rd row is empty I got an error: InvalidArgument=Value of '3' is not valid for 'index'.
so how do i check the row if its empty and what validation should i do if it's empty i will not pass my items to label1.Text and if its not empty it will pass the Items to label1.Text
You have 3 items, So the maximum index is 2 because the index of the array count from 0.
Same principle for the subitem.
Use Items[2] and SubItems[0]
if (listView1.Items[2].SubItems[0].Text == string.Empty)
Indexes in C# start at 0, so a collection that has 3 items would have the indexes of 0, 1 and 2. Based on your question, your if statement should look like this:
if (listView1.Items[2].SubItems[0].Text == string.Empty)
When trying to access something by its index you should typically have some sort of safety check, like checking the .Length or .Count before attempting to access something that could be out of range. You can also leverage some Linq and the null conditional operator to make things a little safer (albeit slightly slower since its enumerating):
//Skip 2, take the 3rd if its there then take the first SubItem.
//label1.Text is either the text or an empty string
label1.Text = listView1.Items.Skip(2).FirstOrDefault()?.SubItems
.FirstOrDefault()?.Text ?? string.Empty;
Related
How can this row give back -1 in index? i have no clue how. there is none of em that can have -1 in index all of them are lists? The lists have values 148, 2999, 620
products.prestaShopCategoryId2.Add(categories2.CategoryPrestaId[categories2.NewCategoryId.FindIndex(a => a.Contains(products.productCategoryId2[j]))]);
I'd suggest you to refactor this code, as it is very hard to read and problems like the one you have becaome very hard to solve. Please, see below code:
var indexOfItem = categories2.NewCategoryId.FindIndex(a => a.Contains(products.productCategoryId2[j]));
// Here you can handle situation, when element is not found and
// returned index is -1
if(indexOfItem == -1)
throw new Exception("Item not found!");
var itemToAdd = categories2.CategoryPrestaId[indexOfItem];
products.prestaShopCategoryId2.Add(itemToAdd);
Additionally, you add some logging along the way or anything that will make your life easier, etc.
https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.list-1.findindex?view=netframework-4.8
Returns Int32 The zero-based index of the first occurrence of an
element that matches the conditions defined by match, if found;
otherwise, -1.
When not found, it is -1.
Read a list of non-negative integer values, sentinel -1 (i.e. end the
program and display the output), and print the list replacing each
sequence of zeros with a single zero.
Example input
100044022000301-1
Then the output will be:
10440220301
the last problem of my list, I don't have a clue how to solve it, I tough in removing the zeros and transforming then in than adding a 0 after that
feels bad
Something like this: Linq (in order to take the value before sentinel -1) and Regular expressions (turn 2 or more consequent 0 into single 0):
given a list we can find out the last value before sentinel as
var value = list
.TakeWhile(item => item != sentinel)
.Last();
to turn two or more consequent 0 into single one we can use Regex:
string removed = Regex.Replace(value.ToString(), "0{2,}", "0");
Code:
// initial " list of non-negative integer values"
// I've declared it as long, since 100044022000301 > int.MaxValue
List<long> list = new List<long>() {
4555223,
123,
456,
100044022000301L, // we want this value (just before the sentinel)
-1L, // sentinel
789,
};
long result = long.Parse(Regex.Replace(list
.TakeWhile(item => item != -1) // up to sentinel
.Last() // last value up to sentinel
.ToString(),
"0{2,}", // change two or more consequent 0
"0")); // into 0
If I have a table , with row with numbers like 70-0002098, lets just call the row, ID
I need the last 4 numbers for all the table rows,
So what I need is something like
foreach(var row in table)
{
var Id = row.ID(but just the last 4 digits)
}
Not sure what format you want to store it as, or what you want to do with it after, but...
Edit: Added an if check for length to avoid index out of bounds condition. Also corrected syntax- SubString() => Substring()
int count = 0;
foreach(var row in table){
string temp = row.ID.ToString();
count += (temp.Length > 5)? Convert.ToInt32(temp.Substring(temp.Length-5, 4)) : Convert.ToInt32(temp);
}
// But I have no idea what datatype you have for that or what
// you want to do (count up the integer values or store in an array or something.
// From here you can do whatever you want.
Your illustration suggests that the RowID is not currently a number (its got a hyphen in it) so I assume its a string
id.Right(4);
will return the right four characters. It doesn't guarantee they are numbers though. Right is an extension method of string which can be easily written, or copied from this thread Right Function in C#?
I have a quick question about listView's and how check if a ListView (which contains null items) has a certain string?
Here is the code which add to sepcific items (under column 5 in the listView). It basically checks if that item appears in Google search or not. If it does, it'll write yes to that specific row, if not it'll leave it blank:
string google2 = http.get("https://www.google.com/search?q=" + textBox1.Text + "");
string[] embedid = getBetweenAll(vid, "type='text/html' href='http://www.youtube.com/watch?v=", "&feature=youtube_gdata'/>");
for (int i = 0; i < embedid.Length; i++)
{
if (google2.Contains(embedid[i]))
{
listView1.Items[i].SubItems.Add("Yes");
}
}
Now what I am trying to do is check if that certain column contains items that say Yes. If it does color them Green if not don't.
Here's the code for that:
if (i.SubItems[5].Text.Contains("Yes"))
{
labelContainsVideo.ForeColor = System.Drawing.Color.Green;
}
My issue is I keep getting an error that says InvalidArgument=Value of '5' is not valid for 'index'.
My hunch is that there are null items in column 5 which might be messing it up but I dont know.
Any idea on how to fix this?
Check the Item to see if the SubItem Collection has the correct Number of values.
i.e.
int threshold = 5;
foreach (ListViewItem item in listView1.Items)
{
if (item.SubItems.Count > threshold)
{
if (item.SubItems[5].Text.Contains("Yes"))
{
// Do your work here
}
}
}
i have this code:
ArrayList list = new ArrayList();
foreach (DataRow dataR in prenume.Rows)
{
foreach (var item in dataR.ItemArray)
{
if (item.Equals(" ")) continue;
list.Add(item);
if (input_string.Equals(item.ToString()) && list.Count > 0 )
{
label_hello.Text = "Hello, " + list[2];
}
}
}
When i'm trying to clear the text showed , i get an error which says:
Index was out of range. Must be non-negative and less than the size
of the collection.
Later edit:
Solution found!I was too tired ... sorry for the question!
Well, you start off with an empty list, and then after adding a single item, you might execute (if input_string equals the first item in the first item array):
label_hello.Text = "Hello, " + list[2];
That's trying to access the third item in the list. It will fail when there's only one item. Why did you pick 2 here?
(As an aside, why are you using ArrayList? The generic List<T> type is preferred.)
It's not clear what you're trying to achieve - if you can give us more context, we have a better chance of helping you.
EDIT: From the comments, it looks like this should be
label_hello.Text = "Hello, " + dataR[2];
However, I suspect the loops are still not right... why would you want to iterate over every value in the table, rather than (say) in just one column?
Ofcourse it will give an error.
label_hello.Text = "Hello, " + list[2];
is wrong.
You have only one element list[0] at that stage.
you're getting your error on the following line
label_hello.Text = "Hello, " + list[2];
The reason why you're getting that error is because there is no list[2]
Now, I can't tell exactly what you're trying to do, but I have a sneaky suspicion that you intend 'item' to be a string of some sort, and you want to access the third character in that string.
Even then, keep in mind that sometimes the user might try to input a string that is not 3 or more characters in length.
If you can give more details about what you're trying to do, we can help you further.