как загрузить список <t>из таблицы данных - PullRequest
0 голосов
/ 02 мая 2018

У меня есть вид сетки, и я пытаюсь загрузить список со столбцом из вида сетки, и я получаю исключение нулевой ссылки

я пробовал это

    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(), чтобы заполнить Combobox

Ответы [ 3 ]

0 голосов
/ 02 мая 2018

вместо использования stringList.Add ((строка) contactDataGridView.Rows [I] .Cells [2] .Value); изменить код на stringList.Add (contactDataGridView.Rows [i] .Cells ["ВАШЕ ИМЯ КОЛОННЫ"]. Значение + "");

0 голосов
/ 02 мая 2018

Используйте метод, который позволяет вам ссылаться на объект (в данном случае это элемент управления) и передавать методу ссылку на этот объект.
Без жестко заданной ссылки на объект ваш метод будет более гибким.

Здесь я передаю методу 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;
}
0 голосов
/ 02 мая 2018
  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;
    }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...