Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
408 views
in Technique[技术] by (71.8m points)

c# - DataTable as DataGrid.ItemsSource

hi i want to bind a DataTable with multiple columns to an DataGrid in codebehind

    var dt = new DataTable();

    dt.Columns.Add(new DataColumn("1"));
    dt.Columns.Add(new DataColumn("2"));
    dt.Columns.Add(new DataColumn("3"));

    dt.Rows.Add(ff.Mo);
    dt.Rows.Add(ff.Di);
    dt.Rows.Add(ff.Mi);
    dt.Rows.Add(ff.Do);
    dt.Rows.Add(ff.Fr);
    dt.Rows.Add(ff.Sa);
    dt.Rows.Add(ff.So);
// ff is a object that contains List<myCellObj>

DataGrid DGrid = new DataGrid();
for (int i = 0; i < 3; i++)
{
   DataGridTemplateColumn templateColumn = new DataGridTemplateColumn();
   templateColumn.HeaderTemplate = HeaderDt;
   templateColumn.CellTemplate = ItemDt; //specified DataTemplate for myCellObj

   DGrid.Columns.Add(templateColumn);
}

now how do i set my dt as ItemsSource, Datacontext or what ever to get it in to my View also if you could provide me a way to bind directly to my Object ff

anything that could help is greatly appreciated

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Assuming you're in WPF simply say:

DGrid.ItemsSource = dt.AsDataView();

No need to manually setup your columns on your DataGrid, assigning the DataTable will set these up for you.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...