我想知道XtraGrid和BandedGrid如何发挥作用并与下层数据绑定。 documentation有一些解释性的tl; dr-text但我缺少一个完整的工作示例来在代码中设置它。所以我花了大约2个小时来搞清楚。基于this blog entry 我想在这里发表我的答案。
如果有更好的方法将各个部分放在一起,如下面的答案,我很乐意了解它。
答案 0 :(得分:3)
首先,您必须知道可以将普通的DataTable绑定到XtraGrid,并且创建带状网格是独立的。
下面您可以看到创建了XtraGrid
的新实例。 MainView设置为BandedGridView
private void LoadAndFillXtraGrid() // object sender, EventArgs e
{
grid = new DevExpress.XtraGrid.GridControl();
grid.Dock = DockStyle.Fill;
// set the MainView to be the BandedGrid you are creating
grid.MainView = GetBandedGridView();
// set the Datasource to a DataTable
grid.DataSource = GetDataTable();
// add the grid to the form
this.Controls.Add(grid);
grid.BringToFront();
}
在grid.MainView = GetBandedGridView();
行之上设置一个BandedGridView作为Xtragrid的MainView。下面你看看如何创建这个BandedGridView
//Create a Banded Grid View including the grindBands and the columns
private BandedGridView GetBandedGridView()
{
BandedGridView bandedView = new BandedGridView();
// Set Customer Band
SetGridBand(bandedView, "Customer",
new string[3] { "CustomerId", "LastName", "FirstName" });
SetGridBand(bandedView, "Address", new string[3] { "PLZ", "City", "Street" });
return bandedView;
}
要设置GridBand,您必须创建一个GridBand并通过为每列调用bandedView.Columns.AddField
将其附加到bandedGridView
private void SetGridBand(BandedGridView bandedView, string gridBandCaption
, string[] columnNames)
{
var gridBand = new GridBand();
gridBand.Caption = gridBandCaption;
int nrOfColumns = columnNames.Length;
BandedGridColumn[] bandedColumns = new BandedGridColumn[nrOfColumns];
for (int i = 0; i < nrOfColumns; i++)
{
bandedColumns[i] = (BandedGridColumn)bandedView.Columns.AddField(columnNames[i]);
bandedColumns[i].OwnerBand = gridBand;
bandedColumns[i].Visible = true;
}
}
DataSource可以是包含一些列的普通DataTable。如果数据表中列的名称与BandedGridColumn的名称匹配,则将自动映射。正如您所看到的,我在数据表中添加了一列NotMapped
,在上面的屏幕截图中看不到:
private DataTable GetDataTable()
{
DataTable dt = new DataTable();
dt.Columns.AddRange(new DataColumn[] {
new DataColumn("CustomerId", typeof(Int32)),
new DataColumn("NotMapped", typeof(Int32)),
new DataColumn("LastName", typeof(String)),
new DataColumn("FirstName", typeof(String)),
new DataColumn("PLZ", typeof(Int32)),
new DataColumn("City", typeof(String)),
new DataColumn("Street", typeof(String))
});
dt.Rows.Add(1, 0, "John", "Barista", 80245, "Manhatten", "Broadway");
dt.Rows.Add(2, 0, "Mike", "Handyman", 87032, "Brooklyn", "Martin Luther Drive");
dt.Rows.Add(3, 0, "Jane", "Teacher", 80245, "Manhatten", "Broadway 7");
dt.Rows.Add(4, 0, "Quentin", "Producer", 80245, "Manhatten", "Broadway 15");
return dt;
}
如果某人有一种更优雅的方式将这些碎片放在一起,我很想知道它。