DatagridView绑定DataTable的变态问题,别打我
我在设计器里定好了DatagridView的表头,如何只取datatable里的数据和
DatagridView的列对应起来,而不是把整个datatable,包括列名都绑到其中。
------解决方案--------------------通过设置DataPropertyName 属性来使列和数据源的列关联起来:
DataGridViewColumn.DataPropertyName 属性
获取或设置数据源属性的名称或与 DataGridViewColumn 绑定的数据库列的名称。
------解决方案--------------------下面的代码示例演示如何选择各列将表示的属性。(MSDN)
private void EnumsAndComboBox_Load(object sender, System.EventArgs e)
{
// Populate the data source.
bindingSource1.Add(new Knight(Title.King, "Uther ", true));
bindingSource1.Add(new Knight(Title.King, "Arthur ", true));
bindingSource1.Add(new Knight(Title.Sir, "Mordred ", false));
bindingSource1.Add(new Knight(Title.Sir, "Gawain ", true));
bindingSource1.Add(new Knight(Title.Sir, "Galahad ", true));
// Initialize the DataGridView.
dataGridView1.AutoGenerateColumns = false;
dataGridView1.AutoSize = true;
dataGridView1.DataSource = bindingSource1;
dataGridView1.Columns.Add(CreateComboBoxWithEnums());
// Initialize and add a text box column.
DataGridViewColumn column = new DataGridViewTextBoxColumn();
column.DataPropertyName = "Name ";
column.Name = "Knight ";
dataGridView1.Columns.Add(column);
// Initialize and add a check box column.
column = new DataGridViewCheckBoxColumn();
column.DataPropertyName = "GoodGuy ";
column.Name = "Good ";
dataGridView1.Columns.Add(column);
// Initialize the form.
this.Controls.Add(dataGridView1);
this.AutoSize = true;
this.Text = "DataGridView object binding demo ";
}
DataGridViewComboBoxColumn CreateComboBoxWithEnums()
{
DataGridViewComboBoxColumn combo = new DataGridViewComboBoxColumn();
combo.DataSource = Enum.GetValues(typeof(Title));
combo.DataPropertyName = "Title ";
combo.Name = "Title ";
return combo;
}
#region "business object "
private class Knight
{
private string hisName;
private bool good;
private Title hisTitle;
public Knight(Title title, string name, bool good)
{
hisTitle = title;
hisName = name;
this.good = good;
}
public Knight()
{
hisTitle = Title.Sir;
hisName = " <enter name> ";
good = true;
}
public string Name
{
get
{
return hisName;
}
set
{
hisName = value;
}
}
public bool GoodGuy
{
get
{
return good;
}
set
{
good = value;
}
}
public Title Title
{
get
{
return hisTitle;
}
set
{
hisTitle = value;
}
}
}
#endregion
------解决方案--------------------设置列的DataPropertyName 属性到你数据源的列名上就可以了
------解决方案--------------------帮顶