ListView.SelectedItems[0] Selection Error - c#

Why is my program returning the following error?
Please be specific thanks.
PS: For whatever reason when there is only one item in the listview it works.
Error: InvalidArgument=Value of '1' is not valid for 'index'. Parameter name: index
Code:
if(e.Control == true)
{
try
{
string s = "";
string sCheck = "";
int select = 0;
int i = 0;
int position = 0;
if (i == 1)
{
i--;
}
if(select >= 1)
{
do
{
select--;
} while (select >= 1);
}
if (position >= 1)
{
do
{
position--;
} while (position >= 1);
}
foreach (object item1 in listView1.Items)
{
if (item1 == listView1.SelectedItems[select])
{
s = listView1.SelectedItems[select].Text;
sCheck = item1.ToString();
MessageBox.Show(item1.ToString());
}
else
{
select++;
}
}
string s1 = "";
foreach (object item in listView1.Items)
{
if (sCheck == item.ToString())
{
MessageBox.Show(item.ToString());
i++;
position++;
}
else
{
position++;
}
}
string s2 = listView1.Items.Count.ToString();
s1 = position.ToString();
if (i == 1)
{
string result = "Item: " + s + " || Position: " + s1 + " || Total Items: " + s2;
MessageBox.Show(result, "ListView Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
catch (Exception ex)
{
MessageBox.Show("Select a Item");
MessageBox.Show(ex.Message);
}

If there are no selected items the code will throw an exception at if (item1 == listView1.SelectedItems[select]) as there is no element at [0] in the collection.
Also, I believe the following code would have the same result as yours:
try
{
foreach (var item in listView1.SelectedItems)
{
MessageBox.Show(item.ToString());
}
if (listView1.SelectedItems.Count == 1)
{
var result = string.Format("Item: {0} || Position: {1} || Total Items: {2}",
listView1.SelectedItems[0], listView1.SelectedItems.Count, listView1.Items.Count);
MessageBox.Show(result, "ListView Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
catch (Exception ex)
{
MessageBox.Show("Select a Item");
MessageBox.Show(ex.Message);
}
The first three if statments are redundant as they occur directly after the variables are assigned (i.e, how could i equal 1 if you've just initialized it to 0?)
The two foreach loops show the same thing (show a message box with the selected items).
Position gets incremented for every selected item so it's always going to equal the total selected items.
If you provide more detail about what exactly you're trying to achieve I will try to help.

Related

How do I display the index of one array if the input matches the index of another array?

I have to show the abbreviations of the provinces of my country when the user types in the name, or show the name when the user types in the province. I have created the 2 arrays so that the indexes match and I am trying to use a for loop to search through the arrays and once they find a match then display the other arrays same index in a textbox. It works only for the first index and even with the first index shows the else error message. What am I doing wrong?
string[] statenames = new string[9] { "Eastern Cape", "Free State", "Gauteng", "KwaZulu-Natal", "Limpopo", "Mpumalanga", "Northern Cape", "North-West", "Western Cape" };
string[] abbreviations = new string[9] { "EC", "FS", "GP", "KZN", "LP", "MP", "NC", "NW", "WC" };
private void btnLook_Click(object sender, EventArgs e)
{
try
{
string name = txtName.Text;
string abbreviation = txtAbbreviation.Text;
if (rbtnAbbreviation.Checked == false && rbtnStateName.Checked == false)
{
MessageBox.Show("Please select what you would like to look up", "Entry Error");
}
if (rbtnAbbreviation.Checked)
{
for (int x = 0; x < statenames.Length; x++)
{
if (name == statenames[x])
{
txtAbbreviation.Text = abbreviations[x];
}
else
{
MessageBox.Show("Please enter a valid province name", "Entry Error");
txtName.Focus();
}
}
}
if (rbtnStateName.Checked)
{
for (int x = 0; x < abbreviations.Length; x++)
{
if (abbreviation == abbreviations[x])
{
txtName.Text = statenames[x];
}
else
{
MessageBox.Show("Please enter a valid province abbreviation", "Entry Error");
txtAbbreviation.Focus();
}
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message + "\n\n" + ex.GetType().ToString() + "\n" + ex.StackTrace, "Exception");
}
}
I think you should add a break to the if conditions. Once you find the name you want you get out of the loop.
if (abbreviation == abbreviations[x])
{
txtName.Text = statenames[x];
break;
}
in-order to prevent the loop from continue checking the rest of the array, and that's what cause the else to be triggered.

How to call function randomly in c# according to checkbox list selection value?

Checkbox List has n items, then combination of selection of items has various logic.
e.g. 4 items in list, then user can select 1, 2 ,3 or 4 items.
when 1 items selected possible case is 4
->if items[0] selected then (random_function[0])
->if items1 selected then (random_function1)
.
.so on
when 2 items selected possible case is 6
->if items[0] & items1 then select (random_function[0] or random_function1)
->if items[0] & items[2] then select (random_function[0] or random_function[2])
.
.so on
when 3 items selected possible case is 3
->if items[0] & items1 & items[2] then select (random_function[0] or random_function1 or random_function[2])
->if items[0] & items1 & items[3] then select (random_function[0] or random_function1 or random_function[3])
.
.so on
when 4 items selected possible case is 1
->if items[0] & items1 & items[2] & items[4] then select (random_function[0] or random_function1 or random_function[2] or random_function[3])
Note.: random_function[i] call randomly
so, each items has each if cases,
it is possible for small number of n, what if value of n is greater than 10 or 20.
I tried for n=4 (checklistbox items) but i have to try for n=15.
How to call these function according items selected combinations.
And following code in button click event:
`
string s = null;
int c = 0;
for (int i = 0; i < checkedListBox1.Items.Count; i++)
{
if (checkedListBox1.GetItemChecked(i))
{
c = c + 1;
}
}
if (c == 1)
{
if (checkedListBox1.GetItemChecked(0))
{ s = " Item one"; }
else if (checkedListBox1.GetItemChecked(1))
{ s = " Item two "; }
else if (checkedListBox1.GetItemChecked(2))
{ s = " Item three "; }
else if (checkedListBox1.GetItemChecked(3))
{ s = " Item four "; }
}
else if (c == 2)
{
Random r = new Random();
int var = r.Next(1, 3);
if (checkedListBox1.GetItemChecked(0) && checkedListBox1.GetItemChecked(1))
{
if (var == 1) { s = " Item one "; }
else { s = " Item two "; }
}
else if (checkedListBox1.GetItemChecked(0) && checkedListBox1.GetItemChecked(2))
{
if (var == 1) { s = " Item one "; }
else { s = " Item three "; }
}
else if (checkedListBox1.GetItemChecked(0) && checkedListBox1.GetItemChecked(3))
{
if (var == 1) { s = " Item one "; }
else { s = " Item four "; }
}
else if (checkedListBox1.GetItemChecked(1) && checkedListBox1.GetItemChecked(2))
{
if (var == 1) { s = " Item two "; }
else { s = " Item three "; }
}
else if (checkedListBox1.GetItemChecked(1) && checkedListBox1.GetItemChecked(3))
{
if (var == 1) { s = " Item two "; }
else { s = " Item four "; }
}
else if (checkedListBox1.GetItemChecked(2) && checkedListBox1.GetItemChecked(3))
{
if (var == 1) { s = " Item three "; }
else { s = " Item four "; }
}
}
else if (c == 3)
{
Random r = new Random();
int var = r.Next(1, 4);
if (checkedListBox1.GetItemChecked(0) && checkedListBox1.GetItemChecked(1) && checkedListBox1.GetItemChecked(2))
{
if (var == 1) { s = " Item one "; }
else if (var == 2) { s = " Item two "; }
else { s = " Item three "; }
}
else if (checkedListBox1.GetItemChecked(0) && checkedListBox1.GetItemChecked(1) && checkedListBox1.GetItemChecked(3))
{
if (var == 1) { s = " Item one "; }
else if (var == 2) { s = " Item two "; }
else { s = " Item three "; }
}
else if (checkedListBox1.GetItemChecked(1) && checkedListBox1.GetItemChecked(2) && checkedListBox1.GetItemChecked(3))
{
if (var == 1) { s = " Item one "; }
else if (var == 2) { s = " Item two "; }
else { s = " Item three "; }
}
}
else if (c == 4)
{
Random r = new Random();
int var = r.Next(1, 4);
if (checkedListBox1.GetItemChecked(0) && checkedListBox1.GetItemChecked(1) && checkedListBox1.GetItemChecked(2) && checkedListBox1.GetItemChecked(3))
{
if (var == 1) { s = " Item one "; }
else if (var == 2) { s = " Item two "; }
else if (var == 3) { s = " Item three "; }
else { s = " Item four "; }
}
}
label1.Text = s; //output
`

DataSet.GetChanges() return exception: Index was out of range. Must be non-negative and less than the size of the collection

Sometimes I get this error in the server:
Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index
-StackTrace-
at System.Collections.BitArray.Get(Int32 index)
at System.Data.DataSet.MarkModifiedRows(TableChanges[] bitMatrix, DataRowState rowStates)
at System.Data.DataSet.GetChanges(DataRowState rowStates)
at System.Data.DataSet.GetChanges()
at MapNetService.DataAccess.GPSDataProcessingProvider.Flush(String name)
I have two servers (production and test) that handle some data and mostly get this error only in one server
The function is very simple
public void Flush(string name)
{
bool isSuccess = true;
try
{
GPSDataProcessingDS changedData = (GPSDataProcessingDS)gpsData.GetChanges();
gpsData.AcceptChanges();
RemoveExcessiveRows(name, gpsData.tblGPSReport);
RemoveExcessiveRows(name, gpsData.tblIOReport);
if (changedData != null
&& (changedData.tblGPSReport.Count > 0 || changedData.tblIOReport.Count > 0
|| changedData.tblLastGPSReadings.Count > 0))
{
isSuccess = SaveChanges(changedData);
}
else
{
Trace.WriteLine("No changes to flush.");
}
}
catch (Exception e)
{
Logger.Log(name, "Flushing exception:" + e.Message);
try
{
if (gpsData.HasErrors)
{
if (gpsData.tblGPSReport.GetErrors().Length > 0)
{
foreach (var error in gpsData.tblGPSReport.GetErrors())
{
Logger.Log(name, "Error:" + error.RowError);
}
}
if (gpsData.tblIOReport.GetErrors().Length > 0)
{
foreach (var error in gpsData.tblIOReport.GetErrors())
{
Logger.Log(name, "Error:" + error.RowError);
}
}
if (gpsData.tblLastGPSReadings.GetErrors().Length > 0)
{
foreach (var error in gpsData.tblLastGPSReadings.GetErrors())
{
Logger.Log(name, "Error:" + error.RowError);
}
}
}
}
catch
{
// ignored
}
gpsData.RejectChanges();
throw;
}
}
The GetErrors() return nothing
Thanks a lot

Additional information: InvalidArgument=Value of '0' is not valid for 'index'

I realize this may look like a duplicate question (I've seen many other questions asking about this error), however I cannot find an answer which explains the issue I'm having. The error is provoked by a call to
invList.SelectedItems[0].Text //invList is a ListView
From what I've read, the error when provoked by this instruction is indicative of attempted access to an empty list (or array?) of selected items in the ListView. However, the ListView I am attempting to access is populated with items at the time of the instruction's execution. Here are the methods in which I issue this instruction:
Method #1: deleteItem
public bool deleteItem()
{
if (invList.SelectedItems.Count == 0) //if no item selected...
{
MessageBox.Show("Error: No item selected", "Error", MessageBoxButtons.OK, MessageBoxIcon.Warning);
return false;
}
else
{
DialogResult dialogResult = MessageBox.Show(
"Are you sure you want to delete item: " + invList.SelectedItems[0].Text + "?",
"Error", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
if (dialogResult == DialogResult.Yes)
{
for (int i = 0; i < itemRecords.Count; i++)
{
if ((itemRecords[i].id.ToString() == invList.SelectedItems[0].Text) && (itemRecords[i].practice == clinicName))
{
itemRecords.Remove(itemRecords[i]);
listRefresh();
}
}
return true; //return true to indicate that data has been edited
}
return false; // return false to indicate that nothing has changed
}
}
Method #2: updateItem
public bool updateItem()
{
if (invList.SelectedItems.Count == 0) //if no item selected
{
MessageBox.Show("Error: No item selected", "Error", MessageBoxButtons.OK, MessageBoxIcon.Warning);
return false;
}
else
{
for (int i = 0; i < itemRecords.Count; i++)
{
//if id == the id of the selected item
if((itemRecords[i].id.ToString() == invList.SelectedItems[0].Text) && (itemRecords[i].practice == this.Text))
{
ItemAddition itemAddition = new ItemAddition(itemRecords, itemRecords[i], this);
itemAddition.ShowDialog();
}
}
return true;
}
}
listRefresh:
public void listRefresh()
{
invList.Items.Clear();
loadItems();
}
loadItems:
private void loadItems()
{
foreach (Record r in itemRecords)
{
if (r.practice == clinicName)
invList.Items.Add(r.ToString());
}
}
The error is invoked when the first method is called, but NOT when the second method is called. This inconsistency is the reason for my confusion. Is there some reason this error would only occur in the first method?
Move refreshing method after remove items. If you move item and rebind, then you will lost selection.
for (int i = 0; i < itemRecords.Count; i++)
{
if ((itemRecords[i].id.ToString() == invList.SelectedItems[0].Text) && (itemRecords[i].practice == clinicName))
{
itemRecords.Remove(itemRecords[i]);
//listRefresh();
}
}
listRefresh();
return true;

Search string in Listbox

I'm having troubles finding a string into a listbox, my string NombreCompleto is made of 3 strings that I previously had read from a file(ESSD), after I had recovered this string, I want to know if this string is in my listbox3, I tried several methods but it doesnt seem to work.
Here is my code.
foreach (string h in Directory.EnumerateFiles(NomDirec, "resume*"))
{
this.listBox1.Items.Add(h);
var NombreLinea = File.ReadLines(h);
foreach (string item in NombreLinea)
{
NombreAbuscar.Add(item.Remove(item.IndexOf(':')));
this.listBox3.Items.Add(item.Remove(item.IndexOf(':')));
}
foreach (string t in Directory.EnumerateFiles(NomDirec, "ESSD1*"))
{
string[] Nombre = File.ReadLines(t).ElementAtOrDefault(6).Split(':');
string[] ApellidoPat = File.ReadLines(t).ElementAtOrDefault(7).Split(':');
string[] ApellidoMat = File.ReadLines(t).ElementAtOrDefault(8).Split(':');
string NombreCompleto = ApellidoPat[1]+" "+ ApellidoMat[1] +","+" "+ Nombre[1];
string Nom2 = NombreCompleto.ToString();
int index = listBox3.FindString(Nom2);
if (index != -1)
{
this.listBox1.Items.Add(t);
MessageBox.Show("Find It");
}
else { MessageBox.Show("Not Found :#"); }
}
You can try with this code - based on Linq operator Where, ...
var selectedItems = from li in listBox3.Items
where li.Text == Nom2
select li.Text;
if(selectedItems.Any())
....
Try this out:
int index = -1;
for (int i = 0; i < listBox3.Items.Count; ++i)
if (listBox3.Items[i].Text == Nom2) { index = i; break; }
if (index != -1)
{
this.listBox1.Items.Add(t);
MessageBox.Show("Find It");
}
else { MessageBox.Show("Not Found :#");
Really easy way to find if a certain string is in a listbox.
private void btnAddRecipe_Click(object sender, EventArgs e)
{
bool DoesItemExist = false;
string searchString = txtRecipeName.Text;
int index = lstRecipes.FindStringExact(searchString, -1);
if (index != -1) DoesItemExist = true;
else DoesItemExist = false;
if (DoesItemExist)
{
//do something
}
else
{
MessageBox.Show("Not found", "Message", MessageBoxButtons.RetryCancel, MessageBoxIcon.Stop);
}
PopulateRecipe();
}

Categories