I have a code to get data by loop each cell of a datagrid, but the code has error, "Object reference not set to an instance of an object".
I think the reason probably is i should not use "grid.Columns[j].GetCellContent(data[i]) as TextBlock". I think I should get the column from ItemsScource, not from the datagrid.
I know "int i = 0; i < data.Count; i++" can loop each row, but how to loop each column, or more precisely how to get data from each cell? Below is the code
private string GetDatagrid(DataGrid grid)
{
var data = (ObservableCollection<ConfigViewModel>)grid.ItemsSource;
StringBuilder dataStr = new StringBuilder();
for (int i = 0; i < data.Count; i++)
{
for (int j = 0; j < grid.Columns.Count; j++)
{
TextBlock selectTextBlockInCell = grid.Columns[j].GetCellContent(data[i]) as TextBlock;
string configVari= selectTextBlockInCell.Text; //This line comes the error!
dataStr.Append(configVari);
dataStr.Append("#");
}
dataStr.Remove(dataStr.Length - 1, 1);
dataStr.Append(@"\\");
}
return dataStr.ToString();
}