0
votes

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();
}
1
That is beacuse grid.Columns[j].GetCellContent(data[i]) does not return a TextBlock, try to debug and check what TYPE does it return - bit

1 Answers

0
votes

The gid.cloumns[j].GetCellContent(Object dataitem) return Framework element in your case it might be returning some other Control other than TextBlock so you casting is not working, that is why your TextBlock is not getting initializes and that is why you are getting Object Reference not set to instance of the object. The other possibility is that you cell may contain null value