Dropdown selection in IE 11 is not working - c#

I am an automation tester and I have automated the dropdown selection. I have a set of elements in a dropdown . I am storing all the values in the dropdown using the below code(I am using the Xpath)
ListItem item = "/container[#caption='selectbox']/listitem[#text='" + comboItem + "']";
As a recent change, our developers have added null value for the first element of a dropdown. Because of this I am getting error in my code and so dropdown selection functionality is not working. By any way is there a chance to catch the null value stored in the List and continue to the store the next value of the dropdown in the list.
I am using the below code to select an element from a dropdown and I am getting error in the above line that has been described in main part of question.
public void SelectfromSelecttag(SelectTag selectTag, string comboItem)
{
try
{
int attemptsToSelect =0;
int maxAttemps = 3;
while(attemptsToSelect != maxAttemps)
{
selectTag.EnsureVisible();
selectTag.Click(Location.CenterRight, 1000);
ListItem item = "/container[#caption='selectbox']/listitem[#text='" + comboItem + "']";
Delay.Milliseconds(1000);
item.Select();
item.MoveTo();
item.Click();
string itemtext = item.Text;
if(itemtext == comboItem)
{
break;
}
else
{
attemptsToSelect++;
}
}
Thread.Sleep(3000);
}
catch (Exception e)
{
Logger.Instance.ErrorLog ("Unable to find Select Item: " + comboItem + e.Message);
}
}

Related

How to filter ListView by using a ComboBox?

I have a TextBox that searches whatever I have in my ListView. I would like to have a ComboBox that will allow the user to “Show All”, “Show Match” and “Show Non Match” within the ListView depending on search criteria.
private void SearchBtn_Click(object sender, EventArgs e)
{
int count = 0, searchStartIndex = selectedIndexPos = 0;
// Clear previously selected indices
listView.SelectedIndices.Clear();
string target = searchTextBox.Text;
// Search for item with text from the search text box, including subItems, from searchStartIndex, not a prefixSearch
ListViewItem item = listView.FindItemWithText(target, true, searchStartIndex, false);
/*----------------------------------------------------------------------------------------------------*
* While the search results in an item found continue searching. *
*----------------------------------------------------------------------------------------------------*/
while (item != null)
{
count++;
// Update progressBar
progressBar.Value = (int)((float)searchStartIndex / listView.VirtualListSize * 100);
ListView.SelectedIndexCollection indexes = listView.SelectedIndices;
if (!indexes.Contains(item.Index))
{
listView.SelectedIndices.Add(item.Index);
}
/*----------------------------------------------------------------------------------------------------*
* Set the start index to the index after the last found, if valid start index search for next item.*
*----------------------------------------------------------------------------------------------------*/
if ((searchStartIndex = item.Index + 1) < listView.VirtualListSize)
{
item = listView.FindItemWithText(searchTextBox.Text, true, searchStartIndex, false);
// count++;
}
else
{
item = null;
}
}
if (listView.SelectedIndices.Count == 0)
{
MessageBox.Show("Find item with text \"" + searchTextBox.Text + "\" has no result.");
}
else
{
RefilterListView();
listView.EnsureVisible(listView.SelectedIndices[0]);
}
}
I would like to have my items in the 'ComboBox' to help filter my 'ListView'. The "Show All" should display all contents of 'ListView' along with item that was searched, the "Show Match" should show only the searched item removing everything else that doesn't match the search and "Show Non Match" should show all of the contents from 'ListView' that doesn't match the searched item.
I can't do it exactly in your case. But I hope I realize it. I mean this is just a solution. You can customize it for your case.
First of all, put a BindingSource on your Form and bind it to your data:
bindingSource1.DataSource = data;
Then bind your ListView(actually DataGridView) to the BindingSource:
dataGridView1.DataSource = bindingSource1;
And then define an enum like this:
public enum Something
{
ShowMatch = 1,
ShowNonMatch = 2
}
Now, put a ComboBox on your Form and add your options to it:
comboBox1.Items.Add("Show All");
comboBox1.Items.Add("ShowMatch");
comboBox1.Items.Add("ShowNonMatch");
comboBox1.SelectedIndex = 0;
After that, you can catch the selected item in SelectedIndexChanged:
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
if (comboBox1.SelectedIndex == 0)
bindingSource1.Filter = null;
else
bindingSource1.Filter = $"Name = '{comboBox1.SelectedItem.ToString()}'";
}

multiple drop down boxes not picking up new elements (Selenium, C#)

I have to drop down boxes I am trying to select using Selenium the first one works fine however when i try to select the second it does not pick up the values and still uses the first set of elements.
public static void AnfoldComboBox(string sComboBoxId, string sItemText)
{
Drivers.CurrentDriver.FindElement(By.CssSelector($"#{sComboBoxId} + .anfold-combobox .anfold-combobox-toggle.ui-corner-right")).Click();
IWebElement dropDownWrapper = Drivers.CurrentDriver.FindElement(By.ClassName("anfold-combobox-autocomplete"));
ReadOnlyCollection<IWebElement> items = dropDownWrapper.FindElements(By.CssSelector(".ui-menu-item > div"));
foreach (IWebElement item in items)
{
if (item.Text.Trim() == sItemText)
{
item.Click();
break;
}
}
Can you please try below code and check you are getting completer list from dropdown first ?
SelectElement test = new SelectElement(driver.FindElement(By.CssSelector(".ui-menu-item > div")));
IList<IWebElement> size = test.Options;
int myitem = size.Count;
for (int i = 0; i < myitem; i++)
{
String value = test.ElementAt(i).Text;
Console.WriteLine(value);
if (val.Equals(sItemText, StringComparison.InvariantCultureIgnoreCase))
{
val.click();
}
else{
Console.WriteLine("Not present");
}
}

C# Selecting multiple results in a listbox search?

I want to search a listbox for a object value i made. This is the override string. This is how items are added into the listbox.
public override string ToString()
{
string reservatiestring;
reservatiestring ="Kamer: " + roomNumber + " Op datum: " + datum + " Aantal personen: " + personen.Count + " Naam: " + reservatienaam;
return reservatiestring;
}
I'd now like to search in my listbox for results while searching for a specific roomNumber. All the roomNumbers are saved in a combobox. This is what i have currently:
private void buttonSearch_Click(object sender, EventArgs e)
{
foreach (var item in listBox1.Items)
{
for (int i = listBox1.Items.Count - 1; i >= 0; i--)
{
if (listBox1.Items[i].ToString().ToLower().Contains(comboBox1.SelectedText.ToLower()))
{
listBox1.SetSelected(i, true);
}
else
{
MessageBox.Show("error");
}
}
This only selects one result though and its not specified to the roomNumber object only. When i put in the foreach to make it select multiple items, my program failed and i got the following error:
The list that this enumerator is bound to has been modified. An enumerator can only be used if the list is not changed
Extra info as asked for!
This is where i add the info to the listbox:
private void btnReserve_Click(object sender, EventArgs e)
{
Reservations reservatie = new Reservations();
reservatie.roomNumber = Convert.ToInt32(numericUpDownroom.Value);
reservatie.datum = dateTimePicker1.Value;
reservatie.reservatienaam = textBoxName1.Text;
for (int i = 0; i <= personcount; i++)
{
Person persoon = new Person();
persoon.naam = textBoxName1.Text;
persoon.leeftijd = Convert.ToInt32(numericUpDownAge1.Value);
reservatie.personen.Add(persoon);
}
if (!comboBox1.Items.Contains(reservatie.roomNumber))
{
comboBox1.Items.Add(reservatie.roomNumber);
}
else
reservaties.Add(reservatie);
listBox1.FormattingEnabled = false;
listBox1.Items.Add(reservatie.ToString());
The error: the error when it pops up. The dutch additional information is the initial error message.
I don't see why you need a foreach to multi select in your case especially that you are not using the "var item" anywhere in the code.
However, the exception might happen if the "SetSelected" implementation is doing some changes internally to the items.
Make sure you have configured your list for multi-select
// Set the selection mode to multiple and extended.
listBox1.SelectionMode = SelectionMode.MultiExtended;
Remove the foreach. (If you still need another loop, replace your foreach with a "for")
Check the below documentation link which has v. good example of multi-select ListBox:
https://msdn.microsoft.com/en-us/library/system.windows.forms.listbox.items(v=vs.110).aspx

Trouble with setting a reference int

I have a page with a listing of products in a table (which is built with divs but I digress), and one column is called "Add to Shopping List" and contains a checkbox. If that checkbox is checked, then the product for that row should be placed into the user's order. On submission, the user is taken to an order review page with all the items they had selected.
The problem right now is that, even though I set the quantity of a product to "1" when the checkbox is selected, every time the form is submitted, the number of items selected for ordering is always 0.
The function that is meant to see if any items have been selected for ordering upon submission is called checkQtys:
protected bool checkQtys(ref int ItemCnt, ref ArrayList LinesToOrder)
{
Repeater locationRepeater = (Repeater)FindControl("locationRepeater");
bool validQtys = true;
string productID = "";
int qty;
qtyErrorMsg.Text = "";
qtyErrorMsgTop.Text = "";
foreach (RepeaterItem repItem in locationRepeater.Items)
{
if (repItem != null)
{
Repeater areaRepeater = (Repeater)repItem.FindControl("areaRepeater");
if (areaRepeater != null)
{
foreach (RepeaterItem skuItm in areaRepeater.Items)
{
if (skuItm != null)
{
Label SkuID = (Label)skuItm.FindControl("SkuID");
Label qtyID = (Label)skuItm.FindControl("qtyID");
PlaceHolder inner = (PlaceHolder)skuItm.FindControl("ProductTable");
if (inner != null)
{
foreach (Control ct in inner.Controls)
{
if (ct is CheckBox)
{
CheckBox lineQty = (CheckBox)ct;
Label prodID = (Label)inner.FindControl("productID");
if (lineQty.Checked)
{
productID = prodID.Text;
qty = 1;
LinesToOrder.Add(new LineItem(productID, qty));
ItemCnt++;
validQtys = true;
}
}
}
}
}
}
}
}
}
return validQtys;
}
*Note: This original was meant to check a textbox value--the "Add To Shopping List" column was originally set to take user input for specific quantities but that has been changed to the checkbox.
This is the submit function:
protected void orderSubmit(object sender, EventArgs e)
{
int ItemCnt = 0;
bool validQtys = true;
ArrayList LinesToOrder = new ArrayList();
Label lb = FindControl("order") as Label;
if (checkQtys(ref ItemCnt, ref LinesToOrder))
{
string value = checkQtys(ref ItemCnt, ref LinesToOrder).ToString();
Response.Write("value: " + value + "<br />");
if (ItemCnt == 0)
{//make sure at least one item with proper qty amount is entered before submitting the order
validQtys = false;
noItemMsg.Visible = true;
noItemMsg.Text = "<br /><br />You must order at least one item<br />";
noItemMsgTop.Visible = true;
noItemMsgTop.Text = "You must order at least one item<br />";
}
if (validQtys)
{//save the information to a session variable and send users to order review page
try
{
foreach (LineItem WorkLine in LinesToOrder)
{
lb.Text += WorkLine.SKUID + ", " + WorkLine.Qty + ";";
}
Session["orderComplete"] = lb.Text;
}
catch (Exception x)
{
Response.Write(x.Message.ToString());
}
Response.Redirect("/united-states/market/office-buildings/obproductmap/OrderReview");
}
}
}
What happens in the above function is that ItemCnt is always 0, and thus the user never can go to the order review page even if they have checked at least one of the checkboxes in the product listing table. I have no clue why this is happening--with the ref int value for ItemCnt being set in checkQtys, it should not be coming in as 0 in orderSubmit unless it is actually 0.
What am I missing?

Finding specific value within a loop

I'm using an Enum within a ComboBox. I want it to allow editing, so that the user can type things in it. I converted the Enum to a string[] arrayItems while listItems is the length of the Enum list.
Now I want to check the users text input: If it isn't listed, it should show a message that the item is not listed there.
But for my code (below) it shows me a error multiple times:
// Converted enum to string[] before
for (int i = 0; i < listItems; i++)
{
if (comboBox1.Text != arrayItems[i])
{
message = string.Format("Sorry! " + comboBox1.Text + " not found.");
}
}
This shows error every time I start it as it iterates through each and every element in the list. I want that if this could check the whole Enum list and give the error once in case of wrong input.
You can change your loop as
bool ok = false;
for (int i = 0; i < listItems; i++)
{
if (comboBox1.Text == arrayItems[i])
{
ok=true;
break;
}
}
if(ok==false)
{
message = string.Format("Sorry! " + comboBox1.Text + " not found.");
}
if(arrayItrmd.Contains(combobox1.Text))
{
//logic if trur
}
You can use LINQ's All for this. As the name implies, it will only be true if all elements correspond to your query. It's basically the equivalent of !Any
if (arrayItrmd.All(item => item != comboBox1.Text))
{
message = string.Format("Sorry! " + comboBox1.Text + " not found.");
}
This means "If each element from arrayItrmd is not equal to comboBox1's text, assign the message."
You can ignore the use of a loop
if(tmpImageArray.FirstOrDefault(a => a == comboBox1.Text) == default(String))
{
message = comboBox1.Text + " not found";
}
else{
message = comboBox1.Text + " found";
}
I have solved this problem like this,
First my enum that I will bind to my combobox
public enum comboboxVals
{
one, two, three
}
Then set my combobox's datasource like this
comboBox1.DataSource = Enum.GetNames(typeof(comboboxVals));
and then implemented code in one of my combobox events to check if the value is valid like combobox Leave, Validating and Validated events..
private void comboBox1_Validating(object sender, CancelEventArgs e)
{
var cbx = sender as ComboBox;
if (!Enum.IsDefined(typeof(comboboxVals), cbx.Text))
{
MessageBox.Show(cbx.Text + " not in the list");
e.Cancel=true;
}
else
{
// Implement your logic here
}
}

Categories