using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Windows.Forms;
namespace AOI
{
/// <summary>
/// 控件绑定数据源
/// </summary>
class MyControlsDataBinding
{
/// <summary>
/// 将界面控件绑定到实体类(控件名必须跟实体类的字段名相同)
/// </summary>
/// <param name="myparams">实体类</param>
/// <param name="f">窗体</param>
/// <param name="dsup">数据绑定模式</param>
public void DataBind(object myparams, Control f, DataSourceUpdateMode dsup)
{
Type type = myparams.GetType();
PropertyInfo[] infos = type.GetProperties();
allcontrols.Clear();
Control[] fcontrols = GetAllControls(f);
foreach (Control item in fcontrols)
{
foreach (PropertyInfo info in infos)
{
if (item.Name == info.Name)
{
string controlproperty = PropertyFromControl(item);
item.DataBindings.Add(controlproperty, myparams, info.Name,true, dsup);
}
}
}
}
/// <summary>
/// 绑定翻译类使用
/// </summary>
/// <param name="myparams"></param>
/// <param name="f"></param>
public void DataBind(object myparams, Control f)
{
Type type = myparams.GetType();
PropertyInfo[] infos = type.GetProperties();
allcontrols.Clear();
Control[] fcontrols = GetAllControls(f);
foreach (Control item in fcontrols)
{
foreach (PropertyInfo info in infos)
{
if (item.Name == info.Name)
{
string controlproperty = PropertyFromControls(item);
item.DataBindings.Add(controlproperty, myparams, info.Name, false, DataSourceUpdateMode.Never);
}
}
}
}
/// <summary>
/// 获取的控件列表
/// </summary>
public List<Control> allcontrols = new List<Control>();
/// <summary>
/// 获取指定控件(窗体)内所有控件
/// </summary>
/// <param name="f">指定控件(窗体)</param>
/// <returns></returns>
private Control[] GetAllControls(Control f)
{
foreach (Control item in f.Controls)
{
allcontrols.Add(item);
if (item.Controls != null)
{
GetAllControls(item);
}
}
return allcontrols.ToArray();
}
/// <summary>
/// 获取指定控件的指定属性
/// </summary>
/// <param name="control">指定控件</param>
/// <returns></returns>
public string PropertyFromControl(Control control)
{
string requestProperty = "Text";
if (control is TextBox || control is Label)
{
requestProperty = "Text";
}
else if (control is CheckBox)
{
requestProperty = "Checked";
}
else if (control is NumericUpDown)
{
requestProperty = "Value";
}
else if (control is ComboBox)
{
requestProperty = "Text";
}
return requestProperty;
}
public string PropertyFromControls(Control control)
{
string requestProperty = "Text";
if (control is TextBox || control is Label || control is CheckBox || control is GroupBox|| control is TreeView)
{
requestProperty = "Text";
}
else if (control is ComboBox)
{
requestProperty = "DataSource";
}
else if (control is DataGridView)
{
requestProperty = "DataSource";
}
return requestProperty;
}
}
}
C#界面控件数据绑定
于 2022-05-18 13:47:47 首次发布