Add<T>
A generic method to add databinding to a control. This method brings type safety for the sake of better code maintainability.
Source
public static Binding Add<T>(this ControlBindingsCollection bindingCollection, string property, object datasource, Expression<Func<T, object>> expression)
{
string relatedNameChain = "";
if (expression.Body is UnaryExpression)
relatedNameChain = ((expression.Body as UnaryExpression).Operand as MemberExpression).ToString();
else if (expression.Body is MemberExpression)
relatedNameChain = (expression.Body as MemberExpression).ToString();
string skippedName = String.Join(".", relatedNameChain.Split(new char[] { '.' }).Skip(1).ToArray());
return bindingCollection.Add(property, datasource, skippedName);
}
Example
var txtName = new System.Windows.Forms.TextBox();
var ds = new System.Windows.Forms.BindingSource();
txtName.DataBindings.Add<tblProduct>("Text", ds, p => p.ProductName, true, DataSourceUpdateMode.OnValidation, "");
Author: Alireza Mokhtaripour
Submitted on: 26 mrt. 2013
Language: C#
Type: System.Windows.Forms.ControlBindingsCollection
Views: 6281