每当我尝试从WPF Datagrid删除选定的行时,它都会正确删除该行,但是“ dataGrid1_SelectionChanged”事件引发一个异常,即对象引用未设置为对象实例。在删除行后,我无法处理这种情况。
private void dataGrid1_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
OrignalSelectedRow = null;
DataGrid gd = (DataGrid)sender;
DataRowView rowSelected = dataGrid1.SelectedItem as DataRowView;
int batchnumber = Convert.ToInt32(rowSelected["b_id"]); //This line is raising Exception
//int batchnumber = batchidval;
label16.Content = batchnumber;
}
行删除代码在下面
private void button6_Click(object sender, RoutedEventArgs e)
{
//Deletion of Row
DataRowView rowSelected = dataGrid1.SelectedItem as DataRowView;
int row_qty = Convert.ToInt32(rowSelected["qty"]);
int row_batch_num = Convert.ToInt32(rowSelected["b_id"]);
//label16.Content = row_batch_num;
label16.Content = row_qty;
con.Open();
try
{
SqlCommand command = new SqlCommand("update batch set sold_qty=sold_qty-@qty2, left_qty=left_qty+@qty2 where id=@id2", con);
command.Parameters.AddWithValue("@qty2", row_qty);
command.Parameters.AddWithValue("@id2", row_batch_num);
rexe = command.ExecuteNonQuery();
}
catch(Exception ex)
{
MessageBox.Show("Updation Error "+ex.ToString());
}
try
{
SqlCommand delcommand = new SqlCommand("DELETE FROM invoice WHERE sr#='" + rowSelected["sr#"] + "'", con);
//con.Open();
delcommand.ExecuteNonQuery();
con.Close();
}
catch(Exception ex)
{
MessageBox.Show("Deletion Error " + ex.ToString());
}
if(rowSelected!=null)
{
dt_1.Rows.Remove(rowSelected.Row); //dt_1 is a DataTable
}
dataGrid1.SelectedItem = 0;
}
答案 0 :(得分:1)
删除该行后,将没有选定的行。这意味着
DataRowView rowSelected = dataGrid1.SelectedItem as DataRowView;
是null
,您无法访问它
rowSelected["b_id"]
一个简单的解决方案是检查null并在未选择任何行的情况下设置默认值:
DataRowView rowSelected = dataGrid1.SelectedItem as DataRowView;
if (rowSelected != null)
{
int batchnumber = Convert.ToInt32(rowSelected["b_id"]);
label16.Content = batchnumber;
}
else
{
label16.Content = "No row selected";
}
更加紧凑:
if (dataGrid1.SelectedItem is DataRowView rowSelected)
{
label16.Content = Convert.ToInt32(rowSelected["b_id"]);
}
else
{
label16.Content = "No row selected";
}