繁体   English   中英

将列添加到DataGridView

[英]Add Columns to DataGridView

我用属性填充列表,并且希望该列表成为dataGridviiew的数据源。

但是,当我将此列表设置为dataGridView作为dataSource时,所有属性值都位于一列中。 如何在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();

            }
        }         
    }
}

我认为您正在尝试执行类似的操作,尽管我不确定,因为您的代码尚不清楚。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM