add columns to datagridview usercontrol
i 开发者_如何学Gocreated an usercontrol for datagridview.
I set it asgridview.autoGeneratecolumn = false;
in the usercontrol.
Question: How do i add columns to the usercontrol in my UI form?
I cannot add default columns to the usercontrol as other UI form might not using the same columns.
If i do not put
gridview.autoGeneratecolumn = false;
, then the auto generated columns will be showing my database columns name instead of the name i want to display to the user.
Extending on the property above
private List<string> _list = new List<string>();
private List<string> ColList
{
get { return _list; }
set { _list = value; }
}
private DataGridViewTextBoxColumn AddColumns(string Name)
{
DataGridViewTextBoxColumn col = new DataGridViewTextBoxColumn()
col.Name = Name;
col.HeaderText = Name;
col.HeaderCell.Style.WrapMode = DataGridViewTriState.NotSet;
col.ToolTipText = Name;
col.AutoSizeMode = DataGridViewAutoSizeColumnMode.ColumnHeader;
col.MinimumWidth = 80;
col.DataPropertyName =Name;
return col;
}
You can then loop through the ColumnList and Add and also set the basic properties for the columns
foreach(string s in ColList)
{ datagridview1.Columns.Add(AddColumns(s)); }
You could always expose the Columns property of the datagridview as a property of your usercontrol.
public partial class MyUserControl : UserControl
{
// This property will be visible in your usercontrols property window in the designer
public DataGridViewColumnCollection Columns
{
get { return dataGridView1.Columns; }
}
public MyUserControl()
{
InitializeComponent();
this.dataGridView1.AutoGenerateColumns = false;
}
}
If you drop your usercontrol onto a form or another control, the Columns property will be accessible in the designer properties window.
Try this link on how to create columns with gridview.autoGeneratecolumn
set to false
精彩评论