简体   繁体   中英

Datagrid binding using DataTable on edit System.NullReferenceException: 'Object reference not set to an instance of an object.'

On Edit of datagrid throws null exception, for datagrid binding using datatable, filling the datatable code is as below in xaml.cs. Datatable binding is working on editing the cells Null exception in presentation framework, framework used is .NET 4.6

//DataTable created in xaml.cs, 
private DataTable _dataTable3cross3 = new DataTable("table3cross3");
public DataTable DataTable3cross3
{
get { return _dataTable3cross3; }
set
{
_dataTable3cross3 = value;
OnPropertyChanged("DataTable3cross3");
}
}
//Xaml
<DataGrid x:Name="grid1" Margin="10" Grid.Column="0" Grid.Row="2"
ItemsSource="{Binding}" BorderThickness="2" ScrollViewer.HorizontalScrollBarVisibility="Disabled"
ScrollViewer.VerticalScrollBarVisibility="Disabled"
HeadersVisibility="Column" GridLinesVisibility="All"
CanUserAddRows="False" CanUserDeleteRows="False" 
CanUserSortColumns = "False" CanUserReorderColumns="False"
CanUserResizeColumns="False" CanUserResizeRows="False" 
RowHeight="36" AutoGenerateColumns="True" AutoGeneratingColumn="r2_AutoGeneratingColumn" VerticalContentAlignment="Center" HorizontalContentAlignment="Center" />

//xaml.cs
private void CreateTable()
{
try
{
//Clearing the columns to update the with new values
_dataTable3cross3.Clear();
_dataTable3cross3.Columns.Clear();
// Adding columns
for (int i = 0; i <= 3; i++)
{ 
if (i == 0)
{
this._dataTable3cross3.Columns.Add("Ranges Values");
}
else
{
this._dataTable3cross3.Columns.Add("T" + i.ToString() + " " + "[c]");
}
}
//Rows added from list
if (TempRangeGasValues3x3.Count > 0)
{
this._dataTable3cross3.Rows.Add(12, 13, 14, 15);
}
if (PressRangeGasValues3x3.Count > 0 && CompZValues3x3.Count > 0)
{
this._dataTable3cross3.Rows.Add(1, 2, 3, 4);
this._dataTable3cross3.Rows.Add(5, 6, 7, 8);
this._dataTable3cross3.Rows.Add(9, 6, 3, 4);
}
grid1.DataContext = DataTable3cross3;
}
catch (Exception ex)
{
}
}

//[Below is the exception on datagrid edit][1]

//[1]: https://i.stack.imgur.com/uJt2w.png

Remove additional space or string in column will resolve issue

this._dataTable3cross3.Columns.Add("T" + i.ToString());

Or Change "[]" braces to "(c)" will also resolve issue.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM