今天闲来无事看到ORm的特性映射sql语句。我就想到datagridview也可以用这个来动态添加列。这样就不用每次都去界面上点开界面填列了。
代码简漏希望有人看到了能指点一二。
先定义好Datagridview要加载的列。
public class Model
{
[ColumnAttribute(type = typeof(DataGridViewTextBoxColumn), DataPName = "d", HText = "sd")]
public int Id { get; set; }
public string Name { get; set; }
}
自定义特性
public class ColumnAttribute : Attribute
{
public Type type { get; set; }
public string DataPName { get; set; }
public string HText { get; set; }
}
定义填加列方法
public DataGridViewColumn[] DgvCArry()
{
Model model = new Model();
PropertyInfo[] property = model.GetType().GetProperties();
DataGridViewColumn[] dgvcArr = new DataGridViewColumn[property.Count() - 1];
for (int i = 0; i < property.Count()-1; i++)
{
object[] pInfo = property[i].GetCustomAttributes(false);
foreach (object objAtt in pInfo)
{
if (objAtt.GetType() != typeof(ColumnAttribute))
{
continue;
}
ColumnAttribute columnAtt = objAtt as ColumnAttribute;
var DgvColumnType = columnAtt.type;
object obj = DgvColumnType.Assembly.CreateInstance(DgvColumnType.FullName);
if (columnAtt.type == typeof(DataGridViewTextBoxColumn))
{
DataGridViewTextBoxColumn dgvtc = obj as DataGridViewTextBoxColumn;
dgvtc = new DataGridViewTextBoxColumn()
{
HeaderText = columnAtt.HText,
DataPropertyName = columnAtt.DataPName,
Name = columnAtt.DataPName
};
dgvcArr[i] = dgvtc;
}
else if (columnAtt.type == typeof(DataGridViewComboBoxColumn))
{
DataGridViewComboBoxColumn dgvcbc = obj as DataGridViewComboBoxColumn;
dgvcbc = new DataGridViewComboBoxColumn()
{
HeaderText = columnAtt.HText,
DataPropertyName = columnAtt.DataPName,
Name = columnAtt.DataPName
};
dgvcArr[i] = dgvcbc;
}
else if (columnAtt.type == typeof(DataGridViewCheckBoxColumn))
{
DataGridViewCheckBoxColumn dgvcbc = obj as DataGridViewCheckBoxColumn;
dgvcbc = new DataGridViewCheckBoxColumn()
{
HeaderText = columnAtt.HText,
DataPropertyName = columnAtt.DataPName,
Name = columnAtt.DataPName
};
dgvcArr[i] = dgvcbc;
}
else if (columnAtt.type == typeof(DataGridViewImageColumn))
{
DataGridViewImageColumn dgvcbc = obj as DataGridViewImageColumn;
dgvcbc = new DataGridViewImageColumn()
{
HeaderText = columnAtt.HText,
DataPropertyName = columnAtt.DataPName,
Name = columnAtt.DataPName
};
dgvcArr[i] = dgvcbc;
}
else if (columnAtt.type == typeof(DataGridViewLinkColumn))
{
DataGridViewLinkColumn dgvcbc = obj as DataGridViewLinkColumn;
dgvcbc = new DataGridViewLinkColumn()
{
HeaderText = columnAtt.HText,
DataPropertyName = columnAtt.DataPName,
Name = columnAtt.DataPName
};
dgvcArr[i] = dgvcbc;
}
else if (columnAtt.type == typeof(DataGridViewButtonColumn))
{
DataGridViewButtonColumn dgvcbc = obj as DataGridViewButtonColumn;
dgvcbc = new DataGridViewButtonColumn()
{
HeaderText = columnAtt.HText,
DataPropertyName = columnAtt.DataPName,
Name = columnAtt.DataPName
};
dgvcArr[i] = dgvcbc;
}
}
}
return dgvcArr;
}
//界面初始化时调用
dataGridView1.Columns.AddRange(DgvCArry());
原文地址:https://www.cnblogs.com/LuoEast/p/8214109.html