簡體   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