multiple drop down boxes not picking up new elements (Selenium, C#) - 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");
}
}

Related

Seeing if a notepad contains the same word as the combo box has selected

So what my problem is and i have looked on the internet for this but really cannot find out how to do it.
I want to use my combo box which is populated with items from a notepad. i want the combo box to search through the notepad when an items from the combo box is selected and when it gets a match i want it to return the line number(ID).
This is what i thought would work, but it doesn't full work.
int items = File.ReadLines(#"C:\Users\PC\Documents\File\IDs.txt").Count();
string line;
int thisnum;
if (cboItemPick.SelectedIndex != -1)
{
if (cboItemPick.SelectedItem != null)
{
for (int i = 0; i <items;)
{
items = i;
line = File.ReadLines(#"C:\Users\PC\Documents\File\IDs.txt").ElementAt(items);
if (line == cboItemPick.Text)
{
MessageBox.Show("Boom");
break;
}
else
{
i++;
}
}
}
}
First of all, your code will have very bad performances. Please refer to this reviewed example:
if( cboItemPick.SelectedItem != null) {
var filepath = #"C:\Users\PC\Documents\File\IDs.txt";
var lines = File.ReadLines(filepath);
var keyword = cboItemPIck.SelectedItem as String;
for(var i = 0; i < lines.length; i++) {
var line = lines[i];
if( string.Compare(line, keyword) == 0) {
// Good, you have a match!
MessageBox.Show(string.Format("Item found at line: {0}", i));
break;
}
}
}
I hope this can help you.
You can try this:
var lines = File.ReadLines(#"C:\Users\PC\Documents\File\IDs.txt");
var result = lines.Select((i, index) => new { Value = i, Index = index }).ToList();
//Check if cboItemPick.SelectedItem is valid and set it to comboboxValue
var lineNumber = result.First(i => i.Value == comboboxValue).Select(i => i.Index);

Custom Objects Listbox Foreach Loop

I have a list of postcodeitems and I bind this to a listbox.
It contains two properties : postcode, area.
I want to loop through the listbox items and if the item is selected, add the postcodeitem object to another list.
List<Valueobjects.postcodeitem> temp = _BL.GetPostCodeAreasFromZones();
PCList.AddRange(temp);
ListBox1.DataSource = PCList;
ListBox1.DataBind();
List<Valueobjects.postcodeitem> postcodecollection = new List<Valueobjects.postcodeitem>();
foreach (ListItem listitem in ListBox1.Items)
{
if (listitem.Selected)
{
i = i + 1;
//Run at 20 to speed up query
if (i == 20)
{
//Get data
CustList.AddRange(BL.SearchCustomerByPostcodeArea(postcodecollection,2));
i = 0;
}
else
{
//add the post code to temp list
postcodecollection.Add(listitem);
}
}
}
if (i > 0)
{
//get data
CustList.AddRange(BL.SearchCustomerByPostcodeArea(postcodecollection,2));
}
}
Obviously where I am trying to add (listitem) isnt going to work as this is a list item and not a postcodeitem. My question is how do I get the postcodeitem object within the list where the list item is selected?
thanks
Try something like following.
IList<Employee> boundList = ListBox1.DataSource
var obj = boundList[ListBox1.SelectedIndex]
Update => I have not tested the code but something like following. Using for loop to track the element index.
for (int i = 0; i< ListBox1.Items.Length; i++)
{
if (ListBox1.Items[i].Selected)
{
i = i + 1;
//Run at 20 to speed up query
if (i == 20)
{
//Get data
CustList.AddRange(BL.SearchCustomerByPostcodeArea(postcodecollection,2));
i = 0;
}
else
{
//add the post code to temp list
postcodecollection.Add(ListBox1.DataSource.ToList().ElementAt(i));
}
}
}
if (i > 0)
{
//get data
CustList.AddRange(BL.SearchCustomerByPostcodeArea(postcodecollection,2));
}
}
Anyways this is not recommended way. You should get selected value and use that selected value(unique field) to fetch relevant data from any persistant storage like database.

Trying to search ListView for subitems matching a string

I'm having trouble scanning through a ListView to locate a subitem matching a given string. Here's my code:
private void dateTimePicker1_ValueChanged(object sender, EventArgs e)
{
string date = datePicker.Value.ToShortDateString();
int count = Program.booker.listView.Items.Count;
for (int i = 0; i < count; i++)
{
ListViewItem lvi = Program.booker.listView.Items[i];
if (lvi.SubItems.Equals(date))
{
MessageBox.Show("Found!", "Alert");
Program.booker.listView.MultiSelect = true;
Program.booker.listView.Items[i].Selected = true;
}
else
{
MessageBox.Show("Nothing found for " + date, "Alert");
}
}
}
The ListView is located on the Booker form, and I'm accessing it from the Filter class. I'd like to search the entire ListView for any items matching my date string. Thanks!
You can use the FindItemWithText method.
ListViewItem searchItem = null;
int index = 0;
do
{
if (index < Program.booker.listView.Items.Count)
{
//true = search subitems
//last false param = no partial matches (remove if you want partial matches)
searchItem = Program.booker.listView.FindItemWithText(date, true, index, false);
if (searchItem != null)
{
index = searchItem.Index + 1;
//rest of code
}
}
else
searchItem =null;
} while (searchItem != null);

Sorting a DropDownList?

I'm curious as to the best route (more looking towards simplicity, not speed or efficiency) to sort a DropDownList in C#/ASP.NET - I've looked at a few recommendations but they aren't clicking well with me. this drop down is giving me list in alphabetical order. But I have to sort out randomly.
Note:I do not have control over how the data comes into the DropDownList - I cannot modify the SQL.
public void populateLocationList()
{
DataTable dt_locations = (DataTable)daa_addresses.GetDataByEventLocations(int_eventid);
if (dt_locations != null && dt_locations.Rows.Count > 0)
{
// Populate locations dropdown menu
// Bind locationsList instead of dt_locations
ddl_locations.DataTextField = "Key";
ddl_locations.DataValueField = "Value";
ddl_locations.DataSource = RemoveDuplicateLocations(dt_locations);
ddl_locations.DataBind();
string location = "";
// Set the selection based upon the query string
if (Request.QueryString["loc"] != null)
{
location = Request.QueryString["loc"];
locationLbl.Text = Request.QueryString["loc"];
locationID.Value = "-1";
}
if (dt_locations.Rows.Count == 1)
{
location = ddl_locations.Items[0].Text;
locationLbl.Text = location;
}
// Set location in drop down list
int int_foundlocation = 0;
bool foundLocation = false;
foreach (ListItem lsi_item in ddl_locations.Items)
{
if (lsi_item.Text.ToLower().Trim() == location.ToLower().Trim())
{
int_foundlocation = ddl_locations.Items.IndexOf(lsi_item);
foundLocation = true;
break;
}
}
ddl_locations.SelectedIndex = int_foundlocation;
if (ddl_locations.Items.Count == 1)
{
// Make location label visible.
locationLbl.Visible = true;
ddl_locations.Visible = false;
}
else
{
locationLbl.Visible = false;
ddl_locations.Visible = true;
}
//* defualt location S for short courses *//
if (!IsPostBack && !foundLocation)
{
ListItem s = ddl_locations.Items.FindByText("S");
int index = 0;
if (s != null)
{
index = ddl_locations.Items.IndexOf(s);
}
ddl_locations.SelectedIndex = index;
ddl_locations.DataBind();
}
}
}
I have to sort out randomly.
You'd have to shuffle rows, probably with something close to this code (borrowed from #configurator's answer):
internal static class Extensions
{
internal static IEnumerable<T> Shuffle<T>(this IEnumerable<T> source, Random rng)
{
T[] elements = source.ToArray();
// Note i > 0 to avoid final pointless iteration
for (int i = elements.Length - 1; i > 0; i--)
{
// Swap element "i" with a random earlier element it (or itself)
int swapIndex = rng.Next(i + 1);
yield return elements[swapIndex];
elements[swapIndex] = elements[i];
// we don't actually perform the swap, we can forget about the
// swapped element because we already returned it.
}
// there is one item remaining that was not returned - we return it now
yield return elements[0];
}
}
Assuming that RemoveDuplicateLocations returns a DataTable the binding part of your code should be changed to:
ddl_locations.DataSource = RemoveDuplicateLocations(dt_locations)
.AsEnumerable()
.Shuffle(new Random())
.CopyToDataTable();

Object reference not set to an instance of an object exception when assigning a list to a listbox

I wrote the following method to load a list box with values that have not been loaded already but I am getting an Object reference not set to an instance of an object exception when assigning the following. Any information would be helpful. Thanks.
lbxCabinetName.Items.Add(cabinetsCurrentNotUsed[i].ToString());
// Defined outside a method
List<string> cabinetsCurrentNotUsed;
// Set value in the constructor
cabinetsCurrentNotUsed = new List<string>();
Here is the whole procedure.
private void selectCabinetToAdd()
{
// Loop through all server and form cabinet types to see if there are matches
for (int x = 0; x < opticalFile.serverCabinetNames.Count; x++)
{
bool cabinetExists = false;
for (int i = 0; i < opticalFile.CabinetValues.Count; i++)
{
if (opticalFile.serverCabinetNames[x].ToString() == opticalFile.CabinetValues[i].ToString())
{
cabinetExists = true;
}
}
// Add cabinets not used to cabinetsCurrentNotUsed List
if (!cabinetExists)
{
cabinetsCurrentNotUsed.Add(opticalFile.serverCabinetNames[x].ToString());
}
}
// Send cabinetsCurrentNotUsed List to list box
for (int i = 0; i < cabinetsCurrentNotUsed.Count; i++)
{
lbxCabinetName.Items.Add(cabinetsCurrentNotUsed[i].ToString());
}
}
You are trying to add a null to the listbox.
Insted of
for (int i = 0; i < cabinetsCurrentNotUsed.Count; i++)
{
lbxCabinetName.Items.Add(cabinetsCurrentNotUsed[i].ToString());
}
use
foreach (string s in cabinetsCurrentNotUsed)
{
if(s != null)
lbxCabinetName.Items.Add(s);
}
NOTE
This part is not relavant to the question. But in your inner for loop after setting cabinetExists = true; you can break out of the inner loop (if atleast one condition is met you can make sure the cabinetExists is true. you don't have to check for the rest of the items in the inner loop)
EDIT
private void selectCabinetToAdd()
{
foreach (string sc in serverCabinetNames)
{
bool cabinetExists = false;
foreach (string cv in CabinetValues)
{
if (sc == cv)
{
cabinetExists = true;
break;
}
}
if (!cabinetExists)
{
cabinetsCurrentNotUsed.Add(sc);
}
}
foreach (string ccnu in cabinetsCurrentNotUsed)
{
if (ccnu != null)
lbxCabinetName.Items.Add(ccnu);
}
}
Also if your listBox can be null, make sure you check that first before populating the listbox.
if(lbxCabinetName != null)
{
selectCabinetToAdd();
}
EDIT 2
Dynamically adding control
ListBox lbxCabinetName = new ListBox();
lbxCabinetName.Location = new System.Drawing.Point(10, 55);
lbxCabinetName.Size = new System.Drawing.Size(130, 95);
this.Controls.Add(lbxCabinetName);
Strings are nullable so at some point you must be doing something similar to:
cabinetsCurrentNotUsed.Add(null);
Either that or as dbaseman said it is possible lbxCabinetName is null but I'm betting that isn't the case.
As an aside, it's not really a problem but if you're using a generic list of strings the ToString() call isn't necessary. You can just do this:
lbxCabinetName.Items.Add(cabinetsCurrentNotUsed[i]);

Categories