BindingSource / BindingNavigator: How to prevent editing of bound DataSource? - vb.net

I created a Data Source with VB.NET and Visual Studio 2005. I dragged the data source onto my dialog, and VS created the text boxes with the members of my linked Object, a System.Windows.Forms.BindingSource and a System.Windows.Forms.BindingNavigator.
I populate the List (called myList), set myList as the DataSource in the BindingSource, and things work peachy except for the fact that I want this to be read-only. If the user changes something in one of the text boxes, it saves the changes.
I tried creating a read-only collection to bind to the BindingSource, but that didn't solve the problem:
Dim detailsDlg As New dlgMyDetails
Dim readOnlyList As New ReadOnlyCollection(Of MyObjects)(myList)
detailsDlg.MyBindingSource.DataSource = readOnlyList
detailsDlg.ShowDialog()
I guess I could disable all of the text boxes, but that seems a bit heavy-handed, plus I'd probably want to change the font color so that it's easier to read.
Ideally, I probably wouldn't care if users were able to set focus to the text boxes, or even edit the contents, but I just wouldn't want any changes to persist. That is, if someone edited something, used the navigator to go to the next record, and then returned, I'd want it as it was before the user played with it.
Any suggestions / guidance?
Thanks in advance!

From a Model-View-Control perspective, the constraint you want is not on the model or control, but the view. The view should restrict what is editable on the screen.
If it truly is read-only, why not go with a read-only user interface element, ie, a label? The reason you do this is to reduce confusion to the user. If it is a textbox, there is a reasonable expectation that at some point the data becomes editable. If this is not the case, then presenting a disabled textbox is likely not the right UI element to present, rather, as mentioned, a label.

Instead of making a ReadOnlyCollection you can change the property in your class (MyObjects) to ReadOnly or add attribute System.ComponentModel.ReadOnly(true) to your property, example:
class Person
{
public Person(int id, string name, string address)
{
_id = id;
Name = name;
Address = address;
}
private int _id = 0;
public int ID { get { return _id; } }
[System.ComponentModel.ReadOnly(true)]
public string Name { get; set; }
public string Address { get; set; }
}
ID and Name is going to be readonly, sorry if the example is in C#. Hope this helps.
Cheers.

Related

Expression Blend WP -> Create design time data from class. Issues with Generics

Im trying to create sample data for WP project in Expression Blend.
It works fine with simple classes, but not with custom generics classes. It can define structure of datasource, display correct structure of my ViewModel, but cannot generate values ie SampleData.xaml is empty.
How can I solve this, press some generate button or is there any other easy way to create design time data without writing everything manually?
I used a bit modified generic class NotifyTaskCompletion from here http://msdn.microsoft.com/en-us/magazine/dn605875.aspx and it is a root of problem. Here is result of generated data schema
The easiest thing to do is probably to create "dummy" types that are used by the designer. They would have the same public properties as your real types, but using concrete types and without any real code. They'd also have a different name. Since data-binding uses duck typing, the fact that the design-time object is a different type than the runtime object doesn't matter. For example, say your real class is:
public class GenericObject<T>
{
public T Thing { get; set; }
/* Lots of other complex code here... */
}
then you might also add:
#if DEBUG
public class GenericObjectDesigner
{
public string Thing { get; set; }
/* No need for any complex code */
}
#endif
Now in Blend, create a data source from the GenericObjectDesigner type and set the Thing property to be some string (eg, Lorum ipsum). You can now drag and drop that onto your design surface.
And in your actual code, you use the non-Designer version of the class, eg:
public MainPage()
{
InitializeComponent();
this.DataContext = new GenericObject<int> { Thing = 42 };
}
This will work fine as long as VS is in Debug mode. In Release mode, the app will still compile and run correctly, but you will see errors about GenericObjectDesigner not existing in your XAML files (you can safely ignore them).

Should I have both text and value in my model for a property that is selected from dropdownlist

In ASP.NET MVC application I have a model named CarSearchCriteria:
public class CarSearchCriteria{
public int CarMake {get;set;} // This is selected from a dropdownlist
public int YearOfFirstReg {get;set;}
public string ModelVariant {get;set}
}
I have two views - one for editing and the other one for viewing. In the editing view for the CarMake property I can do the following. I know I could have used DropDownListFor but didn't want to mess with SelectList for the time being:
<select name="CarMake">
<option value="1">BMW</option>
<option value="2">Mercedes</option>
<option value="3">Toyota</option>
</select>
So the model binding mechanism will easily bind the selected value to the appropriate model property. But what about the reading mode. I can't show 1s or 2s. I need to show BMW, Mercedes and so on. My question is what is the preferred way, do I have to have a property name that holds the actual textual information, something like CarMakeText?
You could have both the identifier (which you currently have) as well as the Make object itself. The latter would never need to be accessed when building the model, but can be accessed when reading the model. A lazy-loaded read-only property often works well for that. Something like this:
public int CarMakeID { get; set; }
public Make CarMake
{
get
{
if (CarMakeID == default(int))
return null;
// fetch the Make from data and return it
}
}
Naturally, this depends a lot on what a Make actually is and where you get it. If there's just some in-memory list somewhere then that should work fine. If fetching an instance of a Make is a little more of an operation (say, fetching from a database) then maybe some in-object caching would be in order in case you need to access it more than once:
public int CarMakeID { get; set; }
private Make _carMake;
public Make CarMake
{
get
{
if (CarMakeID == default(int))
return null;
if (_carMake == null)
// fetch the Make from data and save it to _carMake
return _carMake;
}
}
David's solution is just fine but for some reason I find my own solution to better fit my needs and besides that I find it more elegant. So basically what I do is I create a class that holds the textual descriptions of all the properties that keep just ID. For example, I have the following model:
public class EmployeeModel{
public int EmployeeID {get;set;}
public string FullName {get;set}
*public int DepartmentID {get;set}
*public int SpecialityID {get;set;}
public int Age {get;set;}
}
The properties marked with asterisk are the properties that keep ids of possible many predefined options and when showing we're supposed to show the actual descriptions, not the number representations. So for this purpose, we create a separate class:
public class EmployeeTextValues{
public string DepartmentName {get;set;}
public string SpecialityName {get;set;}
}
And then I just add this class as a property to my model:
public EmployeeTextValues TextValues {get;set;}
After that, it's quite easy to access it from anywhere, including Razor.
P.S. I'm sure that a lot of people will tend to do the following before initializing this property:
Employee emp=new Employee;
emp.Age=25;
emp.TextValues.DepartmentName="Engineering";// Don't do this
If you try to access or set Textvalues.Someproperty you'll get Object reference not set to an instance of an object. So do not forget to set TextValues first to some initialized object. Just a kind reminder, that's all.

Deserializing IEnumerable with private backing field in RavenDb

I've been modeling a domain for a couple of days now and not been thinking at all at persistance but instead focusing on domain logic. Now I'm ready to persist my domain objects, some of which contains IEnumerable of child entities. Using RavenDb, the persistance is 'easy', but when loading my objects back again, all of the IEnumerables are empty.
I've realized this is because they don't have any property setters at all, but instead uses a list as a backing field. The user of the domain aggregate root can add child entities through a public method and not directly on the collection.
private readonly List<VeryImportantPart> _veryImportantParts;
public IEnumerable<VeryImportantPart> VeryImportantParts { get { return _veryImportantParts; } }
And the method for adding, nothing fancy...
public void AddVeryImportantPart(VeryImportantPart part)
{
// some logic...
_veryImportantParts.Add(part);
}
I can fix this by adding a private/protected setter on all my IEnumerables with backing fields but it looks... well... not super sexy.
private List<VeryImportantPart> _veryImportantParts;
public IEnumerable<VeryImportantPart> VeryImportantParts
{
get { return _veryImportantParts; }
protected set { _veryImportantParts = value.ToList(); }
}
Now the RavenDb json serializer will populate my objects on load again, but I'm curious if there isn't a cleaner way of doing this?
I've been fiddeling with the JsonContractResolver but haven't found a solution yet...
I think I've found the root cause of this issue and it's probably due to the fact that many of my entities were created using:
protected MyClass(Guid id, string name, string description) : this()
{ .... }
public static MyClass Create(string name, string description)
{
return new MyClass(Guid.NewGuid(), name, description);
}
When deserializing, RavenDb/Json.net couldn't rebuild my entities in a proper way...
Changing to using a public constructor made all the difference.
Do you need to keep a private backing field? Often an automatic property will do.
public IList<VeryImportantPart> VeryImportantParts { get; protected set; }
When doing so, you may want to initialize your list in the constructor:
VeryImportantParts = new List<VeryImportantPart>();
This is optional, of course, but it allows you to create a new class and start adding to the list right away, before it is persisted. When Raven deserializes a class, it will use the setter to overwrite the default blank list, so this just helps with the first store.
You certainly won't be able to use a readonly field, as it couldn't be replaced during deserialization. It might be possible to write a contract resolver or converter that fills an existing list rather than creating a new one, but that seems like a rather complex solution.
Using an automatic property can add clarity to your code anyway - as it is less confusing whether to use the field or the property.

Update a Property of a Control located inside of a UserControl [duplicate]

I have a control with a inner TextBox. I want to make a direct relationship between the Text property of the UserControl and the Text property of the TextBox. The first thing I realized is that Text was not being displayed in the Properties of the UserControl. Then I added the Browsable(true) attribute.
[Browsable(true)]
public override string Text
{
get
{
return m_textBox.Text;
}
set
{
m_textBox.Text = value;
}
}
Now, the text will be shown for a while, but then is deleted. This is because the information is not written automatically within the xxxx.Designer.cs file. How can this behviour be changed?
You need more attributes:
[EditorBrowsable(EditorBrowsableState.Always)]
[Browsable(true)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
[Bindable(true)]
public override string Text { get; set; }
Reflector is a crucial tool for a .NET developer. It is immediately obvious what you need to do when you use it to look at the UserControl.Text property:
[Bindable(false), EditorBrowsable(EditorBrowsableState.Never), Browsable(false),
DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public override string Text
{
get
{
return base.Text;
}
set
{
base.Text = value;
}
}
Ho showed you what you need to do to cancel these attributes, too bad he didn't show you how he found out. Reflector is was free, download it from redgate.com or check the alternatives here : Something Better than .NET Reflector?
For serialization within the InitializeComponent(), all you need is the DesignerSerializationVisibilityAttribute:
[DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]

What is a good way to do multi-row updates in struts (with struts live)?

Without using DynaForm and it's kin.
I would like to use a POJO data transfer object, e.g., Person:
public class Person {
private Long id;
private String firstName;
private String lastName;
// ... getters / setters for the fields
}
In the struts live action form we would have:
public class PersonUpdateForm extends SLActionForm {
String organization;
Person[] persons; // all the people will be changed to this organization; they're names and so forth can be updated at the same time (stupid, but a client might desire this)
// getters / setters + index setters / getters for persons
}
What would the corresponding html:text tags look like in the JSP to allow this? If I switch to a List persons field and use a lazy-loading list (in commons-collections) how would that change thinsg?
There seems to be no good way to do this in struts-1.2(.9?)
All help is greatly appreciated!!! If you need more context let me know and I can provide some.
Okay, I believe I've figured it out! The trick is to have your indexed getter create an element each time the getPersons() method is called by the populate method of BeanUtils. The code is completed yet, but I got a positive looking result. It's 3:30 and I've been stuck on this a while. Nobody seemded to know the answer, which makes me want to smack them in the head with a trout. As for my own ignorance ... I only have them to blame!
public List<Person> getPersons() {
persons.add(new Person()); // BeanUtils needs to know the list is large enough
return persons;
}
Add your indexed getters and setters too, of course.
I remember how I actually did this. You must pre-initialize the persons List above to the maximum size you expect to transfer. This is because the List is first converted to an array, the properties then set on each element of the array, and finally the List set back using setPersons(...). Therefore, using a lazy-loading List implementation or similar approach (such as that show above) will NOT work with struts live. Here's what you need to do in more detail:
private List<Person> persons = new ArrayList<Person>(MAX_PEOPLE);
public MyConstructor() { for(int i = 0; i < MAX_PEOPLE; i++) persons.add(new Person()); }
public List<Person> getPeopleSubmitted() {
List<Person> copy = new ArrayList<Person>();
for(Person p : persons) {
if(p.getId() != null) copy.add(p);
// id will be set for the submitted elements;
// the others will have a null id
}
return copy; // only the submitted persons returned - not the blank templates
}
That's basically what you have to do! But the real question is - who's using struts live anymore?!