向DataGridView添加列

本文关键字:添加 DataGridView | 更新日期: 2023-09-27 18:08:08

我用属性填充我的列表,我希望这个列表是我的datagridview的数据源。

但是当我将这个列表设置为dataGridView作为数据源时,所有属性值都在一列中。我如何在dataGridView为每个属性添加一列?

下面是我的代码:
private void dataGridView2_CellClick(object sender, DataGridViewCellEventArgs e)
{       
    Restaurant n = new Restaurant );
    foreach (DataGridViewCell cell in dataGridView2.SelectedCells)
    {
        IList<String> lista = new List<String>();
        n.Data = string.Empty;
        n.Data2 = string.Empty;
        int indexOfYourColumn = 9;
        int index2 = 0;
        foreach (DataGridViewRow row in dataGridView1.Rows)
        {
            n.Data = row.Cells[indexOfYourColumn].Value.ToString();
            n.Data2 = row.Cells[index2].Value.ToString();
            if (cell.Value.ToString() == n.Data.ToString())
            {
                lista.Add(n.Data);
                lista.Add(n.Data2);
                dataGridView3.DataSource = lista.Select(x => new { Value = x }).ToList();
            }
        }         
    }
}

向DataGridView添加列

我认为你正在尝试做这样的事情,尽管我不确定,因为从你的代码中有点不清楚。

private void dataGridView2_CellClick(object sender, DataGridViewCellEventArgs e)
{
    /* Place indexes here, there is no need to initialize   *
     * so many integers inside loop if they're not changing */
    int indexOfYourColumn = 9, index2 = 0;
    var restaurantList = new List<Restaurant>();
    foreach (DataGridViewCell cell in dataGridView2.SelectedCells)
    {
        foreach (DataGridViewRow row in dataGridView1.Rows)
        {
            if (cell.Value.ToString() == row.Cells[indexOfYourColumn].Value.ToString())
            {
                restaurantList.Add(new Restaurant()
                {
                    Data  = row.Cells[indexOfYourColumn].Value.ToString(),
                    Data2 = row.Cells[index2].Value.ToString()
                });
            }
        }
    }
    dataGridView3.DataSource = restaurantList;
}