Search code examples
c#sapb1

C# Error : NullReferenceException was unhandled by user code


I am developing a payroll add-on for SAP Business One. I try to select a combobox item that is embedded in a SAP matrix column cell, I keep getting an error:

NullReferenceException was unhandled by user code :Object reference not set to an instance of an object

My Code:


public void HandleMenuEvent(ref SAPbouiCOM.MenuEvent pVal)
{
   // Handle Add Menu
   if (pVal.MenuUID == "1282")
   {
       _form.Freeze(true);
       oMatrix.AddRow();
       _edCode.ValueEx = string.Empty;
       _cmbEDDescription = oMatrix.Columns.Item("EDDesc").Cells.Item(oMatrix.RowCount).Specific;
    
       var earnDeductDescription = Program.Kernel.Get().GetAllEarnDeductMasters().Distinct();
    
       if (_cmbEDDescription.ValidValues.Count > 0)
       {
           // Do nothing
       }
       else
       {
           foreach (var item in earnDeductDescription)
           {
               _cmbEDDescription.ValidValues.Add(item.U_PD_description, string.Empty);
           }
       }
    
       _cmbEDDescription.Select(0, SAPbouiCOM.BoSearchKey.psk_Index);
    
       var edDescValue = string.Empty;
    
       edDescValue = _cmbEDDescription.Value;
    
       var edCode = earnDeductDescription.Where(x => x.U_PD_description.Trim() == edDescValue.Trim()).Select(y => y.U_PD_code).SingleOrDefault();
    
       for (int i = 1; i 

The error occurs on the item changed event

#region ItemChanged
if (pVal.ItemChanged && pVal.ColUID == "EDDesc" && pVal.Before_Action == false)
{
    var earnDeductDescription = Program.Kernel.Get().GetAllEarnDeductMasters().Distinct();
    
    var edDescValue = string.Empty;
    
    edDescValue = _cmbEDDescription.Selected.Value;    x.U_PD_description.Trim() == edDescValue.Trim()).Select(y => y.U_PD_code).SingleOrDefault();
    
    for (int i = 1; i 

This is where I attach a user data source to the SAP column

private void BindMatrixToUserDataSource()
{
    // Get main matrix
    oItem = _form.Items.Item("JournalMat");
    oMatrix = oItem.Specific;
        
    _edDescription = _form.DataSources.UserDataSources.Add("EDDesc", SAPbouiCOM.BoDataType.dt_SHORT_TEXT, 30);
    oColumns = oMatrix.Columns;
    _coledDescription = oColumns.Item("EDDesc");
    _coledDescription.DataBind.SetBound(true, "", "EDDesc");
    
    ...some code
}

Can anyone help me solve this?


Solution

  • My suggestion is that _cmbEDDescription.Selected is null at that moment, because no item is selected in the ComboBox. You might change your code like that:

    var edDescValue = _cmbEDDescription.Selected == null ? string.Empty : _cmbEDDescription.Selected.Value;