FastObjectListView UpdateObject() randomly reorders rows within primary sort - vb.net

Data is a generic List of domain objects.
I click the "Deploy Status" column header to sort on that column.
I have a button that does nothing more than folv.UpdateObject(someObject) .
Every time I press that button, the Deploy Status column maintains its sort, but all rows within the sorted blocks are randomly reordered, as per screenshot.
I have commented out everything in the form's code beyond loading the data, the test button, and the FastObjectListView's column.Add() and .SetObjects(). There are no event handlers wired up for the FastObjectListView. I am not setting PrimarySort or SecondarySort in code; only by clicking with the mouse.

You should be able to fix this problem by either calling Sort after your button's call to UpdateObject or changing your usage of UpdateObject to RefreshObject
Reproducing the problem (C# Repro for the issue in the API)
This seems to reproduce the problem you are having. Run the code, sort the Other column ascending. Click the update button.
public class MainForm : Form
{
public MainForm()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(MainForm));
//
// MainForm
//
this.ClientSize = new System.Drawing.Size(300, 300);
this.Name = "MainForm";
this.ResumeLayout(false);
this.PerformLayout();
var OLVa = new FastObjectListView();
OLVa.Width = 250;
OLVa.Height = 250;
OLVa.Columns.Add(new OLVColumn("ID", "ID"));
OLVa.Columns.Add(new OLVColumn("Other", "Other"));
var l1 = new lolz(1, 3);
OLVa.AddObject(l1);
OLVa.AddObject(new lolz(2,3));
this.Controls.Add(OLVa);
var btn = new Button()
{
Text = "Update",
Top = OLVa.Bottom
};
btn.Click += (s,e)=>OLVa.UpdateObject(l1);
this.Controls.Add(btn);
}
private class lolz
{
public int ID;
public int Other;
public lolz(int id, int other)
{
ID = id;
Other = other;
}
}
}
Fixing the problem
The following would fix it for the above example:
btn.Click += (s,e)=>
{
OLVa.BeginUpdate();
try
{
OLVa.UpdateObject(l1);
OLVa.Sort();
}
finally
{
OLVa.EndUpdate();
}
};

Related

TableViewer with EMF databinding and cell editing - close but not quite

I am going through Tom Shindl's instructions on how to add EMF databinding on to tables, here is my code for the data binding:
protected DataBindingContext initDataBindings() {
//going to use this person instead
Person p = ProjectFactory.eINSTANCE.createPerson();
p.setFirstName("tony");
Committership c = ProjectFactory.eINSTANCE.createCommittership();
c.setName("HELP");
Committership anotherC = ProjectFactory.eINSTANCE.createCommittership();
anotherC.setName("PELASE");
Committership yetAnotherC = ProjectFactory.eINSTANCE.createCommittership();
yetAnotherC.setName("EMERGENCY");
p.getCommittership().add(c);
p.getCommittership().add(anotherC);
p.getCommittership().add(yetAnotherC);
CommandStack cs = new BasicCommandStack();
AdapterFactory af = new ProjectItemProviderAdapterFactory();
EditingDomain editingDomain = new AdapterFactoryEditingDomain(af, cs);
//data binding context
DataBindingContext bindingContext = new DataBindingContext();
//
ObservableListContentProvider listContentProvider = new ObservableListContentProvider();
IObservableMap[] attributeMap = new IObservableMap[1];
attributeMap[0] = EMFEditProperties.value(
editingDomain,
FeaturePath.fromList(ProjectPackage.Literals.COMMITTERSHIP__NAME)
).observeDetail(listContentProvider.getKnownElements());
TableViewerColumn column = new TableViewerColumn(tableViewer, SWT.NONE);
column.getColumn().setText("First Name");
column.getColumn().setWidth(200);
column.setLabelProvider(new GenericMapCellLabelProvider("{0}", attributeMap));
//tableViewer.setLabelProvider(new ObservableMapLabelProvider(attributeMap)); -- no need for this anymore
tableViewer.setContentProvider(listContentProvider);
//instead of giving it this list and doing it the non-EMF way
IObservableList selfList = Properties.selfList(Person.class).observe(p.getCommittership());
//property that you are looking for
IListProperty prop = EMFEditProperties.list(editingDomain, ProjectPackage.Literals.PERSON__COMMITTERSHIP);
IObservableValue master = EMFEditProperties.value(editingDomain, ProjectPackage.Literals.COMMITTERSHIP__NAME)
.observe(p);
/**this should not be returning null, instead it should be a
* list of the values from the person committership EList
*/
IObservableList someList = prop.observeDetail(master);
//set input requires and IObservableList!!
tableViewer.setInput(someList);
//
return bindingContext;
}
ok, now just to talk through what is happening and where I am stuck.
this line here would work for JFace data binding:
IObservableList selfList = Properties.selfList(Person.class).observe(p.getCommittership());
it populates the table happily, it is a list containing the three people I added, nice.
now making it work with EMF databinding, I am trying this:
//property that you are looking for
IListProperty prop = EMFEditProperties.list(editingDomain, ProjectPackage.Literals.PERSON__COMMITTERSHIP);
IObservableValue master = EMFEditProperties.value(editingDomain, ProjectPackage.Literals.COMMITTERSHIP__NAME)
.observe(p);
/**this should not be returning null, instead it should be a
* list of the values from the person committership EList
*/
IObservableList someList = prop.observeDetail(master);
the problem is that someList is empty and hence he table won't populate, could someone explain why?
It is definitely those three line that have some logic problem in there.
What I really want is an IObservableList of observed EMF objects...
help would be really appreciated, since Shindl's tutorial doesn't explain where he go the master from...I thought I would create a master:
IObservableValue master = EMFEditProperties.value(editingDomain, ProjectPackage.Literals.COMMITTERSHIP__NAME)
.observe(p);
and do prop.observeDetail(master)
but it is returning an empty list as I mentioned above...if only I could at least get it do display the data, the closest I have come is having three cells but not data in them.
IObservableList listObservable = prop.observe(p);
tableViewer.setInput(listObservable);
That fixed it for me in terms of viewing the data.
As for editing the cells, I did this in the end:
public class CommittershipNameEditingSupport extends EditingSupport {
private static TableViewer tableViewer;
private final CellEditor editor;
public CommittershipNameEditingSupport(TableViewer tableViewer) {
super(tableViewer);
this.tableViewer = tableViewer;
this.editor = new TextCellEditor(tableViewer.getTable());
}
#Override
protected CellEditor getCellEditor(Object element) {
return editor;
}
#Override
protected boolean canEdit(Object element) {
return true;
}
#Override
protected Object getValue(Object element) {
return ((Committership) element).getName();
}
#Override
protected void setValue(Object element, Object value) {
((Committership) element).setName(String.valueOf(value));
tableViewer.update(element, null);
}
}
and in the main view where I craeted the column I just added the method for cell editing support...it works nicely now :)

XAML: Tap a textbox to enable?

In XAML and WinRT, Is there a way to set up a textbox so that it is disabled for text input until it is tapped.
I tried setting up the Tapped event and then setting the IsEnabled=true, but that only seems to work if the IsEnabled=true in the first place.
I found this on MSDN:
http://social.msdn.microsoft.com/Forums/en-US/winappswithcsharp/thread/708c0949-8b06-40ec-85fd-201139ca8b2d
Talks about adding the TappedEvent manually to the event handled for each TextBox, which is cumbersome, but also doesn't seem to work unless IsEnabled was already set to true.
Basically, I want a form where all textboxes display data but are disabled unless the user taps to enable the box and then type.
You can use IsReadOnly instead of IsEnabled to achieve what you are looking for. In addition, you can set up the tapped event handlers in code easily. I'm not sure if setting up handlers in code is a requirement for this to work, as you noted above; however, it does simplify things.
Here are the details.
In the constructor of your page class (here it is MainPage), call the setup function:
public MainPage()
{
this.InitializeComponent();
// call the setup for the textboxes
SetupTextBoxes();
}
Here is where we do the magic - make all textboxes on this page readonly and set up tap handler:
private void SetupTextBoxes()
{
var tbs = GetVisualChildren<TextBox>(this, true);
foreach (var tb in tbs)
{
tb.IsReadOnly = true;
tb.AddHandler(TappedEvent, new TappedEventHandler(tb_Tapped), true);
}
}
Utility function to get a list of all children of the given type (T) of the passed in parent.
private List<T> GetVisualChildren<T>(DependencyObject parent, bool recurse = true)
where T : DependencyObject
{
var children = new List<T>();
int numVisuals = VisualTreeHelper.GetChildrenCount(parent);
for (int i = 0; i < numVisuals; i++)
{
DependencyObject v = (DependencyObject)VisualTreeHelper.GetChild(parent, i);
var child = v as T;
if (child == null && recurse)
{
var myChildren = GetVisualChildren<T>(v, recurse);
children.AddRange(myChildren);
}
if (child != null)
children.Add(child);
}
return children;
}
Finally, the event handler. This enables each textbox when tapped.
private void tb_Tapped(object sender, TappedRoutedEventArgs e)
{
((TextBox)(sender)).IsReadOnly = false;
}

datagridview with datasource out of bound index

I'm binding some fields to a datagridview with
myDataGridView.datasource = List(of MyCustomObject)
And i never touch the indexes manually but i'm getting -1 index have no value (so, an out of bound error)
The error comes on the onRowEnter() Event when I select any row in the grid.
It doesn't even enter any of my events for handling my clic, it bugs before...
On the interface,just before clicking,
I can see that no rows of grid 2 is the (currentRow).
I guess the bug comes from there but I don't know how to set a currentRow Manually or simply avoid this bug...
Any one have seen this before?
edit -
I've added some code to test:
dgvAssDet.CurrentCell = dgvAssDet.Rows(0).Cells(0)
When this assignation runs, the currentCell = nothing,
there is > 5 rows and columns...
And i've got the same error, before changing the old currentCell it trys to retrieve it,
but in my case there is none and it bugs... I've got no idea why.
When you use a DataSource on a DGV, you should use the collection System.ComponentModel.BindingList<T>, not System.Collections.Generic.List<T>
public class MyObject
{
public int Field1 { get; set; }
public MyObject() { }
}
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
DataGridViewTest();
}
public void DataGridViewTest() {
BindingList<MyObject> objects = new BindingList<MyObject>();
dataGridView1.AutoGenerateColumns = true;
dataGridView1.DataSource = objects;
dataGridView1.AllowUserToAddRows = true;
objects.Add(new MyObject() {
Field1 = 1
});
}
}
If your objects list was the type of List<T> you would get the index out of bounds error.

Telerik Mail Merge - Friendly Names (using RadRichTextBox)

I think i'm missing something obvious...
I'm using the Telerik Rad controls for WPF but i assume that the Rich text box uses some similar implementation for the mail merge functionality.
I want to have some friendly names on my mail merge fields. (namely spaces in the field names)
So i have a class for instance
Public Class someclass
{
<DisplayName("This is the complex description of the field")>
Public property thisfieldnamehasacomplexdescription as string
Public property anothercomplexfield as string
}
This is the only way i know to get "Friendly" names in the dropdown that is the mail merge.
So the two fields turn up okay as :
"This is the complex description of the field"
"anothercomplexfield"
but only anothercomplexfield actually populates with data when you do the merge.
Am i going to have to template the raddropdownbutton that holds the mail merge fields?
Is there an example of this somewhere?
Also a sub question. How do i add a scroll bar on these things?
(also i know this board is not a TELERIK specific board (duh!) but this might be useful to someone in the future. So i'll copy the answer i get from Telerik into here!
http://www.telerik.com/community/forums/wpf/richtextbox/558428-radrichtextbox-mailmerge---using-displayname-to-create-a-friendly-name-with-spaces.aspx )
This is what telerik gave me:
With the default MergeFields, it is not possible to change the display name fragment of the field in order to achieve a more friendly look. This should be possible if you implement a custom MergeField by deriving from the MergeField class. Here is a sample implementation that shows how this can be done:
public class CustomMergeField : MergeField
{
private const string CustomFieldName = "CustomField";
static CustomMergeField()
{
CodeBasedFieldFactory.RegisterFieldType(CustomMergeField.CustomFieldName, () => { return new CustomMergeField(); });
}
public override string FieldTypeName
{
get
{
return CustomMergeField.CustomFieldName;
}
}
public override Field CreateInstance()
{
return new CustomMergeField();
}
protected override DocumentFragment GetDisplayNameFragment()
{
return base.CreateFragmentFromText(string.Format(Field.DisplayNameFragmentFormat, this.GetFriendlyFieldName(this.PropertyPath)));
}
private string GetFriendlyFieldName(string fieldName)
{
int lettersInEnglishAlphabet = 26;
List<char> separators = new List<char>(lettersInEnglishAlphabet);
for (int i = 0; i < lettersInEnglishAlphabet; i++)
{
separators.Add((char)('A' + i));
}
StringBuilder newFieldName = new StringBuilder();
int previousIndex = 0;
for (int i = 1; i < fieldName.Length; i++)
{
if (separators.Contains(fieldName[i]))
{
if (previousIndex > 0)
{
newFieldName.Append(" ");
}
newFieldName.Append(fieldName.Substring(previousIndex, i - previousIndex));
previousIndex = i;
}
}
newFieldName.Append(" " + fieldName.Substring(previousIndex));
return newFieldName.ToString();
}
}
Note that the fragment that is shown when the DisplayMode is Code cannot be changed.
As for your other question, you can change the content of the dropdown button to show the friendly name of the fields and to include a scrollbar in the following way:
1. First, remove the binding of the button to the InsertMergeFieldEmptyCommand from XAML and give it a name (e.g. insertMergeField).
2. Next, add the following code in code-behind:
AddMergeFieldsInDropDownContent(this.insertMergeFieldButton);
private void AddMergeFieldsInDropDownContent(RadRibbonDropDownButton radRibbonDropDownButton)
{
Grid grid = new Grid();
grid.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(100, GridUnitType.Pixel) });
ScrollViewer scrollViewer = new ScrollViewer();
scrollViewer.VerticalScrollBarVisibility = ScrollBarVisibility.Auto;
StackPanel stackPanel = new StackPanel();
foreach (string fieldName in this.editor.Document.MailMergeDataSource.GetColumnNames())
{
RadRibbonButton fieldButton = new RadRibbonButton()
{
Text = this.GetFriendlyFieldName(fieldName),
Size = ButtonSize.Medium,
HorizontalAlignment = HorizontalAlignment.Stretch,
HorizontalContentAlignment = HorizontalAlignment.Left
};
fieldButton.Command = this.editor.Commands.InsertFieldCommand;
fieldButton.CommandParameter = new MergeField() { PropertyPath = fieldName };
//or
//fieldButton.CommandParameter = new CustomMergeField() { PropertyPath = fieldName };
stackPanel.Children.Add(fieldButton);
}
stackPanel.HorizontalAlignment = System.Windows.HorizontalAlignment.Stretch;
scrollViewer.Content = stackPanel;
grid.Children.Add(scrollViewer);
radRibbonDropDownButton.DropDownContent = grid;
}
You can, of course optimize the code of the GetFriendlyName method and add it in a way that will be available by both classes.

Cannot get data updates on NotifyPropertyChanged collection

I'm building a Mango app that writes data to a SqlCe database; I have a ListBox bound to a DataSource that must show items when they are added to the database, but when I add/update data I cannot get updates and they are only shown when I reload the page.
Here are some snippets:
public class TimeTrackerViewModel: INotifyPropertyChanged, INotifyPropertyChanging
{
private List<TimeItems> _timeItems;
public List<TimeItems> TimeItems
{
get { return _timeItems; }
set
{
NotifyPropertyChanging("TimeItems");
_timeItems = value;
NotifyPropertyChanged("TimeItems");
}
}
public void LoadCollectionsFromDatabase()
{
// Specify the query for all to-do items in the database.
var times = from t in db.Times
select new TimeItems
{
DtIn = t.DtIn,
DtOut = t.DtOut,
Id = t.Id
};
// Query the database and load all to-do items.
TimeItems = new List<TimeItems>(times);
}
.....
.....
}
When I add data to the Times table I don't see db updates to the listBox bound to the TimeItems collection.
What am I doing wrong?
Make TimeItems an ObservableCollection