dsfg
dsfg

Reputation: 29

Error when get data from the datagrid

Below code is to get the first column data from a datagrid, and do some string operation, but error showed,

NullReferenceException was handled Object reference not set to an instance of an object.

What is the problem ? If I want to get each data in the first column, how to do it?

private string getit(DataGrid grid)
{
    StringBuilder stringStr = new StringBuilder();

    for (int i = 0; i < grid.Items.Count; i++)
    {
        TextBlock selectTextBlockInCell = grid.Columns[0].GetCellContent(i) as TextBlock;
        string inputName = selectTextBlockInCell.Text;

        stringStr.Append(@"\pic () at (-0.5,");
        stringStr.Append(3 - i);
        stringStr.Append(inputName);
        stringStr.Append(@"}");
    }

    return stringStr.ToString();
}

Upvotes: 0

Views: 423

Answers (1)

har07
har07

Reputation: 89285

Read MSDN documentation about DataGridColumn.GetCellContent(), especially about what parameter you should pass to the method. Then you'll know that it doesn't receive row index, but "data item that is represented by the row that contains the intended cell".

Try to operate on underlying data source of the DataGrid instead, for example :

//cast to correct type
var data = (ObservableCollection<MyClass>)grid.ItemsSource;
StringBuilder stringStr = new StringBuilder();
//loop through your data instead of DataGrid it self
for (int i = 0; i < data.Count; i++)
{
    //get the value from correct property of your class model
    string inputName = data[i].MyProperty;
    //or if you really have to get it from cell content :
    //TextBlock selectTextBlockInCell = grid.Columns[0].GetCellContent(data[i]) as TextBlock;
    //string inputName = selectTextBlockInCell.Text;

    stringStr.Append(@"\pic () at (-0.5,");
    stringStr.Append(3 - i);
    stringStr.Append(inputName);
    stringStr.Append(@"}");
}
return stringStr.ToString();

WPF meant to be used with data-binding so that we can have clear separation between UI and data (read about MVVM pattern). Application logic shouldn't care about UI, so it better off operating on UI controls. Do logic operations over model/viewmodel instead, and let data binding pass the model/viewmodel to UI/view.

*) Getting data from data.ItemsSource is just simplified way, to start from what OP has at the moment. The ultimate way is to have a property that store the data and bind ItemsSource to that property.

Upvotes: 1

Related Questions