Datagridview与变量列如何?

时间:2014-09-29 18:17:38

标签: c# datagridview

我是C#的新手,想要使用datagridview,其中两个第一列在每次都是相同的,其余的我依赖于字符串列表的内容。但是我该怎么做呢?

我的代码现在看起来像这样,我可以看到失败,但不知道该怎么办:(

Plz帮助我:)

        View.Columns.Clear();
        View.AutoGenerateColumns = false;

        DataGridViewTextBoxColumn colTime = new DataGridViewTextBoxColumn();
        colTime.DataPropertyName = "Time";
        colTime.HeaderText = "Time";
        colTime.Name = "Time";
        colTime.Width = 55;
        View.Columns.Add(colTime);

        DataGridViewTextBoxColumn colPlace = new DataGridViewTextBoxColumn();
        colPlace.DataPropertyName = "Place";
        colPlace.HeaderText = "Place";
        colPlace.Name = "Place";
        colPlace.Width = 55;
        View.Columns.Add(colPlace);


        for(int i = 0; i < Liste.Length; i++)
        {
            DataGridViewCheckBoxColumn "Log"+List[i] = new DataGridViewCheckBoxColumn();
            "Log"+List[i].DataPropertyName = "List[i]";
            "Log"+List[i].HeaderText = "List[i]";
            "Log"+List[i].Name = "List[i]";
            "Log"+List[i].Width = 55;
            View.Columns.Add("Log"+List[i]);
        }

提前致谢

1 个答案:

答案 0 :(得分:0)

您可以使用此功能自动创建典型的DataGridView

DataGridView CreateDataGridDynamically(int NumberOfCol)
{
    DataGridView D = new DataGridView();
    for (int i = 0; i < NumberOfCol; i++)
    {

        DataGridViewTextBoxColumn C1 = new DataGridViewTextBoxColumn();
        C1.HeaderText = "Something";
        D.Columns.Add(C1);
    }
    return D;
}

并且使用datagridview.Rows.Add()和第四次重载,您只需添加一些约束行:

DataGridView D = CreateDataGridDynamically(3);
D.Rows.Add("Sth1", "Sth1", "Sth3");
D.Rows.Add("Sth1", "Sth1", "Sth3");
D.Rows.Add("Sth1", "Sth1", "Sth3");
Controls.Add(D);