How to handle autocomplete list in webdriver? - select

How to select country name from auto-complete drop down list?
Please provide suggestion with code for Google search so that i can understand.

If your dropdown is editable you can directly type the values using send keys, else you need to simulate the Arrow down key actions as you needed. But it not wise once, because if new values are added in the drop down(Anyway in this case, there will be fixed because the number of countries is a constant),then it will get messed.
driver.findElement(locator).sendKeys(countryName , Keys.TAB);
or
driver.findElement(locator).sendKeys(Keys.DOWN);

Try the following code:
WebElement dropdown = driver.findElement(By.....);
Select dropdownSelect = new Select(dropdown);
dropdownSelect.selectByVisibleText(itemStr) or selectByValue(value);

Link : http://www.mythoughts.co.in/2012/05/getting-google-search-auto-suggestions.html#.Ul-lJdi1Zbc
#Test
public void SearchSuggestion() {
driver.get("http://google.com");
driver.findElement(By.id("gbqfq")).sendKeys("vam");
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
WebElement table = driver.findElement(By.className("gssb_m"));
List<webelement> rows = table.findElements(By.tagName("tr"));
Iterator<webelement> i = rows.iterator();
System.out.println("-----------------------------------------");
while(i.hasNext()) {
WebElement row = i.next();
List<webelement> columns = row.findElements(By.tagName("td"));
Iterator<webelement> j = columns.iterator();
while(j.hasNext()) {
WebElement column = j.next();
System.out.println(column.getText());
}
System.out.println("");
System.out.println("-----------------------------------------");
}
}
}

driver.findElement(By.id("your searchBox")).sendKeys("your partial keyword");
Thread.sleep(3000);
List <WebElement> listItems = driver.findElements(By.xpath("your list item locator"));
listItems.get(0).click();
driver.findElement(By.id("your searchButton")).click()

Related

How to set default select in TwinColSelect Vaadin

I want preselect items in the containerAllClienteByAsociado, I try to preselect the same items in the containerAllCliente but also not found, sorry for bad english.
TwinColSelect colListClientes = new TwinColSelect();
private generateColListClientes(Asociado asociadoInstance){
clienteController = new ClienteController();
//Obtenemos el container con los datos
BeanItemContainer<Cliente> containerAllCliente = new BeanItemContainer<Cliente>(Cliente.class);
containerAllCliente.addAll(clienteController.getCollectionCliente());
BeanItemContainer<Cliente> containerAllClienteByAsociado = new BeanItemContainer<Cliente>(Cliente.class);
containerAllClienteByAsociado.addAll(asociadoInstance.getClientes());
colListClientes.setMultiSelect(true);
colListClientes.setImmediate(true);
colListClientes.setContainerDataSource(containerAllCliente);
colListClientes.setLeftColumnCaption("Listado de Clientes");
colListClientes.setRightColumnCaption("Clientes del Asociado");
colListClientes.setMultiSelect(true);
for (clienteTotales in containerAllCliente){
colListClientes.setValue(clienteTotales);
}
return colListClientes;
}
Instead of this:
`BeanItemContainer<Cliente> containerAllCliente = new BeanItemContainer<Cliente>(Cliente.class);`
Use this:
`BeanContainer<String,Cliente> containerAllCliente = new BeanContainer<String,Cliente>(Cliente.class);`
Also, while populating your twin-select, set its "id" property to be some identifying member variable/property of the Cliente.class
After populating, you can use:
twin-select.setValue(<value of identifying member data of the particular Cliente instance>);
This link might be of help:
https://dev.vaadin.com/svn/doc/book-examples/trunk/src/com/vaadin/book/examples/datamodel/BeanContainerExample.java
I hope it helps.
Instead of using setValue(...) for each item, just use it once and pass the whole collection as argument.
When using setValue(...) with single items, it deselects the previously selected values.
This is my solution, work fine in my code.
private generateColListClientes(Asociado asociadoInstance){
clienteController = new ClienteController();
//DEFINITION OF CONTAINERS
HashSet<Cliente> containerAllCliente = new HashSet<Cliente>();
containerAllCliente.addAll(clienteController.getCollectionCliente());
HashSet<Cliente> containerAllClienteByAsociado = new HashSet<Cliente>()
containerAllClienteByAsociado.addAll(asociadoInstance.getClientes())
//DEFINITION OF TWINCOLUMN
colListClientes.setLeftColumnCaption("Listado de Clientes");
colListClientes.setRightColumnCaption("Clientes del Asociado");
colListClientes.setMultiSelect(true);
colListClientes.setWidth("350px");
colListClientes.setImmediate(true);
HashSet<Cliente> preselected = new HashSet<Cliente>();
//TOUR TOTAL CLIENTS
for (Cliente cliente : containerAllCliente){
colListClientes.addItem(cliente);
//WE COMPARE TOTAL CLIENTS TO ASOCIADO.CLIENTES
for(Cliente clienteAsociado : containerAllClienteByAsociado) {
//COMPARE IDS AND PRESELECT IF IS THE SAME
if(cliente.id==clienteAsociado.id){
preselected.add(cliente);
}
}
}
colListClientes.setValue(preselected);
return colListClientes;
}

How can we access the actual element in Selenium-webdriver (Java)?

In selenium-webdriver (Java),
We can get the GWT element
for eg. WebElement obj = driver.findElement(By.id("gwt-debug-celltable"));
By obj we can get that webelement of the celltable but we won't get the actual celltable. So if want to check the number of records in the celltable using Selenium-Webdriver. What i need to do?
Is it possible? If yes please answer asap.
Yes. You can do it using xpath, somehow:
List<WebElement> elements =
driver.findElements(By.xpath("//table[#id='gwt-debug-celltable']/tbody/tr"));
In elements will be the list of rows. I have not tested this code. But it likes one that we are using in our project.
For the webtable i have refered the below link http://money.rediff.com/gainers/bsc/daily/groupa
from the below code you can get all the values from the webtable
public class MaxFromTable {
public static void main(String[] args) throws ParseException {
WebDriver wd;
System.setProperty("webdriver.chrome.driver","G://chromedriver.exe");
wd= new ChromeDriver();
wd.get("http://money.rediff.com/gainers/bsc/daily/groupa?");
String max;
double m=0,r=0;
//No. of Columns
List col = wd.findElements(By.xpath(".//[#id='leftcontainer']/table/thead/tr/th"));
System.out.println("Total No of columns are : " +col.size());
//No.of rows
List rows = wd.findElements(By.xpath (".//*[#id='leftcontainer']/table/tbody/tr/td[1]"));
System.out.println("Total No of rows are : " + rows.size());
for (int i =1;i<rows.size();i++)
{
max= wd.findElement(By.xpath("html/body/div[1]/div[5]/table/tbody/tr[" + (i+1)+ "]/td[4]")).getText();
NumberFormat f =NumberFormat.getNumberInstance();
Number num = f.parse(max);
max = num.toString();
m = Double.parseDouble(max);
if(m>r)
{
r=m;
}
}
System.out.println("Maximum current price is : "+ r);
}
}

How to filter datagridview using text inputted from a rich text box?

I have a datagridview that I want to display a data from a database. But I don't want it to display all of the data. I want it to display the data for a specific ID only. Meaning if the user enters 3 ID, it will display the info for that 3 ID. Hence I want to use a rich text box as a filter so that the user can enter multiple ID for each line in the rich text box. The user can enter the ID No. within the rich text box and the data will be used as a filter to display the data for that particular ID. But I cannot make it read beyond the first line of the rich text box. If I enter just one ID in the first line, it works perfectly, but if I enter a second ID in the second line, or in the third line, then it will not display anything at all. I tried using for loop to read each line of the rich text box but it doesn't work. Any advice or solution??
here is my code :
namespace TrackCon
{
public partial class trackInput : Form
{
public trackInput()
{
InitializeComponent();
}
/*private void trackInput_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'trackingBMSDATADataSet.BRDATA' table. You can move, or remove it, as needed.
this.bRDATATableAdapter.Fill(this.trackingBMSDATADataSet.BRDATA);
}*/
private void trackBtn_Click(object sender, EventArgs e)
{
RichTextBox dynamicRichTextBox = new RichTextBox();
DataTable dt = null;
string connoInput = richTextBox1.Text;
string conString = Properties.Settings.Default.BMSDATAConnectionString;
//string[] RichTextBoxLines = dynamicRichTextBox.Lines;
foreach (char line in richTextBox1.Text)
{
using (SqlCeConnection con = new SqlCeConnection(#"Data Source=C:\Documents and Settings\Administrator\My Documents\Visual Studio 2008\Projects\TrackCon\TrackCon\BMSDATA.sdf;Persist Security Info = True;Password=xxxx"))
{
con.Open();
SqlCeCommand com = new SqlCeCommand("SELECT conno,cmpsno,ctrx,dsysdate,cstnno,corigin FROM BRDATA WHERE conno = '" + richTextBox1.Text + "'OR cmpsno = '" + richTextBox1.Text + "'", con);
SqlCeDataAdapter adap = new SqlCeDataAdapter(com);
DataSet set = new DataSet();
adap.Fill(set);
if (set.Tables.Count > 0)
{
dt = set.Tables[0];
}
dataGridView1.DataSource = dt;
con.Close();
}
}
}
}
}
I suggest to use a TextBox and set MultiLine to true.
Then you can read all the ids like this:
string[] ids = myTextBox.Text.Split('\n');
EDIT:
You can use SQL's IN to find all elements:
string sql = "SELECT conno, etc FROM BRDATA WHERE conno IN (" + String.Join(", ", ids) + ")";

GWT Sorting a cell table, probably just something i didn't saw

I've been struggling for the last couple of hour trying to sort a GWT CellTable.
It's really a stupid problem because it's been done here
http://gwt.google.com/samples/Showcase/Showcase.html#!CwCellTable
But I do not understand what I'm missing in the exemple ...
Here is my code I use to create the column:
Column<RemoteCommand, String> nbProducts = new Column<RemoteCommand, String>(
new TextCell()) {
#Override
public String getValue(RemoteCommand object) {
return object.getNumberProduct();
}
};
nbProducts.setSortable(true);
sortHandler.setComparator(nbProducts, new Comparator<RemoteCommand>() {
public int compare(RemoteCommand o1, RemoteCommand o2) {
cellTable.redraw();
return o1.getCommandSize().compareTo(o2.getCommandSize());
// System.out.println(Integer.parseInt(o1.getCommandSize() ) - Integer.parseInt(o2.getCommandSize()));
// return Integer.parseInt(o1.getCommandSize() ) - Integer.parseInt(o2.getCommandSize());
}
});
And here is the declaration of the table itself:
// Add a selection model so we can select cells.
final SelectionModel<RemoteCommand> selectionModel = new MultiSelectionModel<RemoteCommand>(
RemoteCommand.KEY_PROVIDER);
cellTable.setSelectionModel(selectionModel,
DefaultSelectionEventManager.<RemoteCommand> createCheckboxManager());
// Attach a column sort handler to the ListDataProvider to sort the list.
ListHandler<RemoteCommand> sortHandler = new ListHandler<RemoteCommand>(values);
cellTable.addColumnSortHandler(sortHandler);
// Initialize the columns.
initTableColumns(selectionModel, sortHandler);
cellTable.setRowData(values);
help is requierd :)
i guess You've already found the solution, but just to keep it here:
First, create your dataProvider with some known List.
Than feed sortHandler with same List;
and use the list to update data.
Celltable should be set as dataDisplay of the dataProvider:
List myDataList = new ArrayList();
ListDataProvider dataProvider = new ListDataProvider(KEY_PROVIDER);
dataProvider.setList(myDataList);
ListHandler sortHandler = new ListHandler(dataProvider.getList);
//tie provider and table
dataProvider.addDataDisplay(cellTable);
//when you need to update dataprovider
//first do some myDataList cleanup to remove old values
myListData.addAll(values);
//update data displays
dataProvider.refresh();
Consider, you have to always use one and the same List object.

Word/Office Automation - How to retrieve selected value from a Drop-down form field

I am trying to retrieve the value of all fields in a word document via office automation using c#. The code is shown below however if the field is a drop-down then the value of the range text is always empty even though I know it is populated. If it is a simple text field then I can see the range text. How do I get the selected drop down item? I feel there must be something quite simple that I'm doing wrong...
private void OpenWordDoc(string filename) {
Microsoft.Office.Interop.Word.Application app = new Microsoft.Office.Interop.Word.Application();
Document doc = app.Documents.Open(filename, ReadOnly: true, Visible: false);
foreach (Field f in doc.Fields) {
string bookmarkName = "??";
if (f.Code.Bookmarks.Count > 0) {
bookmarkName = f.Code.Bookmarks[1].Name; // have to start at 1 because it is vb style!
}
Debug.WriteLine(bookmarkName);
Debug.WriteLine(f.Result.Text); // This is empty when it is a drop down field
}
doc.Close();
app.Quit();
}
Aha - If I scan through FormFields instead of Fields then all is good...
foreach (FormField f in doc.FormFields) {
string bookmarkName = "??";
if (ff.Range.Bookmarks.Count > 0) {
bookmarkName = ff.Range.Bookmarks[1].Name; // have to start at 1 because it is vb style!
}
Debug.WriteLine(bookmarkName);
Debug.WriteLine(ff.Result); // This is empty when it is a drop down field
}
Problem solved. Phew.