How to set default select in TwinColSelect Vaadin - select

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;
}

Related

Need clarification about how to apply a custom update to data adapter source

I have created a record-view form that contains a few bound elements via a BindingSource and a BindingNavigator. The viewing of the data fields is operating correctly. Note that the variables da and ds are global in this form.
private void frmItem_Load(object sender, EventArgs e) {
string scon = System.Configuration.ConfigurationManager.ConnectionStrings["myitems"].ToString();
da = new SqlDataAdapter("Select * From myitems where id > 0 ", scon);
ds = new DataSet();
da.Fill(ds);
bindingSource1.DataSource = ds.Tables[0];
bindingNavigator1.BindingSource = this.bindingSource1;
this.txtId.DataBindings.Add(new Binding("Text", bindingSource1, "id", true));
this.txtItem.DataBindings.Add(new Binding("Text", bindingSource1, "item", true));
this.txtUpdatedwhen.DataBindings.Add(new Binding("Text", bindingSource1, "updatedwhen", true));
}
I am showing this record-view form from a data grid view of items by using a row header mouse dbl-click event. The requested row from the dgv is correctly being selected and its row data is correctly being shown in the record-view form.
private void dgvItems_RowHeaderMouseDoubleClick(object sender, DataGridViewCellMouseEventArgs e) {
frmItem gfrmItem = new frmItem();
string sID = this.dgvItems.CurrentRow.Cells[0].Value.ToString();
gfrmItem.FilterByID(sID);
gfrmItem.Show();
}
I've added a save button to the navigator so that I can make individual record save. What I'm attempting to do is programatically apply a date/time stamp update before the record is saved from the button click.
private void btnSave_Click(object sender, EventArgs e)
{
this.txtUpdatedwhen.Text = DateTime.Now.ToString();
da.Update(ds);
}
Although the date/time value is changed per the code and shows in the form, the update is not applying the date/time change.
I thought that the textbox value was being bound to the underlying dataset and would accept changes as if I had entered it manually ... but this is not occurring. I had read some other posts that using the data adapter update is the right way to go about this as apposed to doing something like performing a direct sql update.
I'm stumped with how to resolve this. Any pointers would be greatly appreciated.
After letting this sit a while and coming back to it today, I found a resolution.
There was a common misunderstanding at work that I saw in other posts.
That was that the dataadapter does not automatically populate its commands, even if you pass an active connection into the creation step.
So my resolution was to create a global SqlCommandBuilder variable along with the other ones I was using
SqlDataAdapter da;
SqlConnection sc;
SqlCommandBuilder sb;
DataSet ds;
then create the builder object at form load and initialize the update command into a string variable ... which isn't used there after, but the dataadapter commands are now populated.
string scon = System.Configuration.ConfigurationManager.ConnectionStrings["networkadmin"].ToString();
sc = new SqlConnection(scon);
sc.Open();
string sSelect = "Select * From datatable where id > 0 Order By fld1;";
}
this.da = new SqlDataAdapter(sSelect, sc);
sb = new SqlCommandBuilder(da);
// This initiates the commands, though the target var is not used again.
string uCmd = sb.GetUpdateCommand().ToString();
this.ds = new DataSet();
this.da.Fill(this.ds);
Then the update step does work as expected:
this.txtUpdatedwhen.Text = DateTime.Now.ToString();
DataRowView current = (DataRowView)bindingSource1.Current;
current["updatedwhen"] = this.txtUpdatedwhen.Text;
bindingSource1.EndEdit();
this.da.Update(ds);
I hope this helps someone.

Writing textlist in codesys

How should I write a text list in CODESYS dynamically at runtime ?
I am using the text list as a source to display in a combo box (drop down list box)
Thanks in advance
First, you need to get the text list factory using the ComponentManager to create an instance:
const Guid TextListFactoryGuid = new Guid("{7a60005b-e690-45b3-8aca-cd15950a3e73}");
var textListFactory = (IObjectFactory)ComponentManager.Singleton.CreateInstance(TextListFactoryGuid);
Then, create an instance of the test list object itself:
var textListObject = (ITextListObject)textListFactory.Create();
The text list object will need to be added to the object manager:
SystemInstances.ObjectManager.AddObject(
SystemInstances.Engine.Projects.PrimaryProject.Handle,
parentGuid,
Guid.NewGuid(),
textListObject,
textListName,
-1);
Finally, now that you have the ITextListObject, you can add strings to it an id and an item:
textListObject.AddEmptyRow();
var textListElement = textListObject.GetTextListRowAt(textListObject.Count - 1);
textListElement.ID = id;
textListElement.Default = item;
Hope that's what you're after

How to handle autocomplete list in webdriver?

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()

Using Drag-Sort ListView with SQLite DB

I'm trying to create a simple to-do-list app with an SQLite DB and a Drag-Sort ListView.
Right now I am binding data from an SQLite database cursor into a ListView using a SimpleCursorAdapter and adding items with an EditText view as explained in this tutorial.
I have moved everything into one activity and I have swapped the plain ListView with a Drag-Sort ListView. My issue is connecting the DB and Drag-Sort ListView together. The DLSV demos use a predefined array to fill fill the DSLV.
Snippet form DSLV:
DragSortListView lv = (DragSortListView) getListView();
lv.setDropListener(onDrop);
lv.setRemoveListener(onRemove);
array = getResources().getStringArray(R.array.jazz_artist_names);
list = new ArrayList<String>(Arrays.asList(array));
adapter = new ArrayAdapter<String>(this, R.layout.list_item1, R.id.text1, list);
setListAdapter(adapter);
Snippet from my existing code:
mDbHelper = new NotesDbAdapter(this);
mDbHelper.open();
...
mDbHelper.createNote(noteName, "");
fillData();
private void fillData() {
// Get all of the notes from the database and create the item list
Cursor c = mDbHelper.fetchAllNotes();
startManagingCursor(c);
String[] from = new String[] { NotesDbAdapter.KEY_TITLE };
int[] to = new int[] { R.id.text1 };
// Now create an array adapter and set it to display using our row
SimpleCursorAdapter notes =
new SimpleCursorAdapter(this, R.layout.notes_row, c, from, to);
setListAdapter(notes);
}
Thank you and sorry if this doesn't make all that much sense.
Since you cannot reorder the items in a Cursor, you have to create a mapping between Cursor positions and ListView positions. This is done for you by the DragSortCursorAdapter class and subclasses so that the drag and drop reordering is maintained visually. If you need the new orders persisted (like to your database), then you must implement that logic yourself. The method getCursorPositions() will help you with this.
I have made use of Drag sort list view. Its amazing! but instead of using the dragsortcursoradapter i created my own trick. here it is.
What i have done is that whenever i swapped any item, i passed the new swapped list in an array to the database, deleted the table and recreated the new updated table. here is my code
here is the code snippet from my database handler
public void onUpdateToDoTable(ArrayList<Task> taskList) {
SQLiteDatabase db = this.getWritableDatabase();
db.execSQL("DROP TABLE IF EXISTS " + TABLE_TASKTODO);
String CREATE_TASK_TODO_TABLE = "CREATE TABLE IF NOT EXISTS "
+ TABLE_TASKTODO + "(" + SEQ_ID + " INTEGER PRIMARY KEY,"
+ TASK_NAME + " TEXT )";
db.execSQL(CREATE_TASK_TODO_TABLE);
for (int i = 0; i < taskList.size(); i++) {
ContentValues values = new ContentValues();
values.put(TASK_NAME, taskList.get(i).getTask());
db.insert(TABLE_TASKTODO, null, values);
}
db.close();
}
then on using drop listener
i called the above method..
private DragSortListView.DropListener onDrop = new DragSortListView.DropListener() {
#Override
public void drop(int from, int to) {
Task item = adapter.getItem(from);
adapter.notifyDataSetChanged();
adapter.remove(item);
adapter.insert(item, to);
db.onUpdateToDoTable(list);
Log.d("LIST", db.getAllToDoTasks().toString());
}
};
db is my object of database handler. whole source code is available at dragdroplistview. amazing example. this was a life saver for me. Ciao!
There is a github project available at https://github.com/jmmcreynolds/dslv-db-demo
This demo includes a working example of how to setup a DragSortListView that will save the changes that you make to the list (position, add/delete) to a database.
I have used it just now. Its perfect demo project available for using DSLV with SQLiteDB.
Thanks to github user jmmcreynolds.

asp.net mvc 2 render view to string, instead of partial

I have this function:
public static string RenderViewToString(string controlName, object viewData) {
ViewDataDictionary vd = new ViewDataDictionary(viewData);
ViewPage vp = new ViewPage { ViewData = vd };
Control control = vp.LoadControl(controlName);
vp.Controls.Add(control);
StringBuilder sb = new StringBuilder();
using (StringWriter sw = new StringWriter(sb))
{
using (HtmlTextWriter tw = new HtmlTextWriter(sw))
{
vp.RenderControl(tw);
}
}
return sb.ToString();
}
And I call it like this:
string body = StringHelpers.RenderViewToString("~/Areas/Public/Views/Shared/RegistrationEmail.ascx", new RegistrationEmailViewModel { User = user });
And it returns a html-table with the user-info.
But I was wondering if there is a way to edit this to I can can return a View as string? so I can add masterpage, so it'll be easier to design all potential mails going out?
Thanks in advance
/M
Check out MVCContrib's email template system for sending emails.
http://codevanced.net/post/Sending-HTML-emails-with-ASPNET-MVC2-and-MVCContrib.aspx
Update:
This question and/or this article might help if you don't want to include Mvccontrib. Although I use Mvccontrib every day, it's harmless.