2

i have a gridview and i am trying to load up the list with a column from the grid view and i m getting a null reference exception

i have tried this

    public static List<string> LoadStringList()
    {
        List<string> stringList = new List<string>();

        if (contactDataGridView.RowCount != 0)
        {
            for (int i = 0; i < contactDataGridView.Rows.Count; i++)
            {
                stringList.Add((string)contactDataGridView.Rows[i].Cells[2].Value);
            }

        }
        return stringList;
    }

and i tried this

    public static List<string> LoadStringList()
    {
        List<string> stringList = new List<string>();

        if (frmPRG299.mainForm.contactDataGridView.RowCount != 0)
        {
            for (int i = 0; i <frmPRG299.mainForm.contactDataGridView.Rows.Count; i++)
            {
                stringList.Add((string)frmPRG299.mainForm.contactDataGridView.Rows[i].Cells[2].Value);
            }

        }
        return stringList;
    }

farther explanation

i have two forms frmMain and frmSub where the gridview is in frmMain and a combobox in frmSub i need to call the function LoadStringList() to populate the Combobox

Andrey Kaplun
  • 100
  • 11
  • Mostly other users will redirect you here: [What is a NullReferenceException, and how do I fix it?](https://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it/4660186#4660186) – Jeroen van Langen May 02 '18 at 18:02
  • try to check for null or empty before adding it into stringList. try using using as instead of cast. – Viju May 02 '18 at 18:02
  • @Viju i need to cast because i need convert the object type to string type – Andrey Kaplun May 02 '18 at 18:06
  • 2
    Remove the static word from the function and try referencing the actual objects. Or, change your call to `public static List LoadStringList(DataGridView dgv)` and pass the existing control as a reference. – LarsTech May 02 '18 at 18:08
  • You can always do var stringData = contactDataGridView.Rows[i].Cells[2].Value as string; if(!string.IsNullOrEmpty(stringData )) { add stringData to stringList } – Viju May 02 '18 at 18:08
  • @LarsTech i have two forms one with a datagridview and one with a combobox and i need the list to populate the combobox and i need to use the function to – Andrey Kaplun May 02 '18 at 18:14
  • @LarsTech why remove the static keyword ? – Andrey Kaplun May 02 '18 at 18:32
  • If you don't know what "static" does, why did you put it in your function? – LarsTech May 02 '18 at 18:41

3 Answers3

0

Instead of using stringList.Add((string)contactDataGridView.Rows[i].Cells[2].Value); chaange the code to stringList.Add(contactDataGridView.Rows[i].Cells["YOUR COLUMN NAME"].Value+"");

babin raj
  • 147
  • 1
  • 7
0

Use a method that allows you to reference an object (a Control in this case), and pass to the method a reference to that object.
Without a hard-coded object reference, your method is more flexible.

Here I'm passing to the method a DataGridView control reference and a cell number from which to extract the current value.

Since the Cell.Value could be null, you have to verify it before attempting to read it and/or transforming it to the required type.

List<string> MyList = LoadStringList(this.dataGridView1, 2);


public List<string> LoadStringList(DataGridView dgv, int cell)
{
    if ((dgv == null) || (dgv.RowCount == 0)) return null;

    List<string> result = dgv.Rows.Cast< DataGridViewRow>()
        .Select(r => { return r.Cells[cell].Value != null 
                            ? r.Cells[cell].Value.ToString() 
                            : default; })
        .ToList();

    return result;
}

If a more generic input type is needed:

try
{ 
    List<int> MyList = LoadList<int>(this.dataGridView1, 2).ToList();
}
catch (Exception ex)
{
    //Handle the exception/Update the UI/Prompt the User
    Console.WriteLine(ex.Message);
}


public IEnumerable<T> LoadList<T>(DataGridView dgv, int cell)
{
    if ((dgv == null) || (dgv.RowCount == 0)) return null;

    IEnumerable<T> result = null;

    try
    {
        result = dgv.Rows.Cast<DataGridViewRow>()
                         .Select(r => { return r.Cells[cell].Value != null
                                   ? (T)Convert.ChangeType(r.Cells[cell].Value, typeof(T))
                                   : default;
                            })
                         .ToList();
    }
    catch (Exception ex) {
        //Manage the exception as required
        throw ex;
    }
    return result;
}
Jimi
  • 22,563
  • 6
  • 34
  • 49
-1
  public List<string> LoadStringList(DataGridView contactDataGridView)
    {
        List<string> stringList = new List<string>();

        if (contactDataGridView.RowCount != 0)
        {
            for (int i = 0; i < contactDataGridView.Rows.Count; i++)
            {
                var stringData = contactDataGridView.Rows[i].Cells[2].Value as string;
                if(!string.IsNullOrEmpty(stringData))
                {
                    stringList.Add(stringData);
                }
            }

        }
        return stringList;
    }
Andrey Kaplun
  • 100
  • 11
Viju
  • 95
  • 1
  • 7
  • will not work because object reference is required for the non-static field, method, or property 'frmPRG299.contactDataGridView' – Andrey Kaplun May 02 '18 at 18:17
  • why remove the static keyword ? could you explain – Andrey Kaplun May 02 '18 at 18:31
  • if contactDataGridView was accessible in the instance then static would not work , But if you are passing the DataGridView to the method it can be static. – Viju May 02 '18 at 18:36