首页 > 解决方案 > 如何加载列表从数据网格视图

问题描述

我有一个gridview,我正在尝试使用网格视图中的一列加载列表,并且我得到一个空引用异常

我试过这个

    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;
    }

我试过这个

    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;
    }

进一步解释

我有两种形式frmMain和frmSub,其中gridview在frmMain和一个组合框在frmSub我需要调用函数LoadStringList()来填充组合框

标签: c#datagridview

解决方案


使用允许您引用对象(在本例中为 Control)的方法,并将对该对象的引用传递给该方法。
如果没有硬编码的对象引用,您的方法会更加灵活。

在这里,我将一个DataGridView控件引用和一个从中提取当前值的单元格编号传递给该方法。

由于Cell.Value可能是null,您必须在尝试读取它和/或将其转换为所需类型之前对其进行验证。

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;
}

如果需要更通用的输入类型:

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;
}

推荐阅读