-2

I try to make an application in C# running on .NET Core 3.1. While compiling, I get no errors and the application runs perfectly on the developed PC but if I publish the application and move it to another machine I get below error and I can not identify what is the cause.

I tried a few actions found on google (to update all visual studio, clear %appdata% files .)

"Object reference not set to an instance of an object
Void Program_Form_Load(Object sender, EventArgs)
at Application.Proogram_Form....... Program_Form.cs:Line 98

At line 98 I have:

private void Program_Form_Load(object sender, EventArgs e)
{
    // MULTIPLE LINES 
    Load_Data.Load_To_CMBB_ Ldt = new Load_Data.Load_To_CMBB_();
    Ldt.Load_Data_ToCombobox(dataGridView4, 0, Fabricant);
    // MULTIPLE LINES 
}

Which is calling:

public void Load_Data_ToCombobox(DataGridView dgw, int Row, ComboBox cmb)
{
    string val = null;
    List<string> l = new List<string>();
    l.Clear();

    for (int i = 0; i <= dgw.Rows.Count - 1; i++)
    {
        if (dgw[Row, i].Value != null)
        {
            val = dgw[Row, i].Value.ToString();

            if (!l.Exists(x => x == val)) 
            { 
                l.Add(val); 
                cmb.Items.Add(val); 
            }
        }
    }

    cmb.SelectedIndex = cmb.Items.Count - 1;
}
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459

1 Answers1

0

Try this:

public void Load_Data_ToCombobox(DataGridView dgw, int Row, ComboBox cmb)
{
    if(dgw?.Rows?.Count == 0) return; //fix#1, you can throw exception too
    string val = null;
    List<string> l = new List<string>();
    l.Clear();
    for (int i = 0; i <= dgw.Rows.Count - 1; i++)
    {
        if (dgw[Row, i].Value != null)
        {
            val = dgw[Row, i].Value.ToString();
            if (!l.Exists(x => x == val)) { l.Add(val); cmb.Items.Add(val); }
        }
    }
    cmb.SelectedIndex = cmb.Items?.Count == 0 ? 0: cmb.Items.Count - 1; //fix#2
}
Kali
  • 1
  • 1
  • When `dgw` or `dgw.Rows` is _null_, `if(dgw?.Rows?.Count == 0) return;` is not doing what you think it does. –  Sep 01 '22 at 20:02
  • Thank you for your help but i get the same errors ... But you say that my error is due to null "values"?? – Stoica Vasile Sep 01 '22 at 20:28
  • If the exception was in this method, then you would expect the name of this method (Load_Data_ToCombobox) should appear in the stack trace. – sgmoore Sep 01 '22 at 21:31