【WPF】遍历DataGrid

2017-06-20 19:26:47来源:CSDN作者:u014234260人点击

网上找了遍历DataGrid,但是都不能用,终于组合出来了~~

///<summary>

/// 获取DataGrid遍历后的数据

///</summary>

///<param name="dg"></param>

///<returns></returns>

publicstring DataGrid(DataGrid dg)

{

try

{

string str = "";

for (int j = 0; j < dg.Items.Count; j++)

{

DataGridCell c = DataGridHelper.GetCell(dg, j, 0);

TextBlock tb = c.Content asTextBlock;

if (str.Equals(string.Empty))

{

str = tb.Text;

}

else

{

str = str +"!" + tb.Text;//直接获取datagrid 遍历后的当前数据

}

}

 return str;

}

catch

{

 returnnull;

}

}


Class :

以下代码网上扒的~~~~

staticclassDataGridHelper




{



staticpublicDataGridCell GetCell(DataGrid dg, int row, int column)




{



DataGridRow rowContainer = GR(dg, row);


if (rowContainer != null)




{



DataGridCellsPresenter p = GC<DataGridCellsPresenter>(rowContainer);


DataGridCell cell = (DataGridCell)p.ItemContainerGenerator.ContainerFromIndex(column);


if (cell == null)




{


dg.ScrollIntoView(rowContainer, dg.Columns[column]);



cell = (DataGridCell)p.ItemContainerGenerator.ContainerFromIndex(column);




}



return cell;




}



else




{



returnnull;




}


}


 


 



staticpublicDataGridRow GR(DataGrid dg, int index)




{



DataGridRow r = (DataGridRow)dg.ItemContainerGenerator.ContainerFromIndex(index);


if (r == null)




{


dg.ScrollIntoView(dg.Items[index]);



r = (DataGridRow)dg.ItemContainerGenerator.ContainerFromIndex(index);




}




return r;




}


 


 



static T GC<T>(Visual parent) where T : Visual




{



T child =default(T);


int numVisuals = VisualTreeHelper.GetChildrenCount(parent);


for (int i = 0; i < numVisuals; i++)




{



Visual v = (Visual)VisualTreeHelper.GetChild(parent, i);


child = vas T;


if (child == null)




{


child = GC<T>(v);


}



if (child != null)




{



break;




}


}



return child;




}


}




            





       




最新文章

123

最新摄影

微信扫一扫

第七城市微信公众平台