C#:DataGridView单元格对齐所有行都不一样?

时间:2014-08-05 10:47:19

标签: c# datagridview

我再次询问C#。我刚刚在DataGridView上加载了我的数据但是我的问题(不是真正的问题)是所有行的单元格对齐都不一样,我想要的是让信息像任何DataGridView一样正常但是这就是我的意思得到:

enter image description here

我试图像这样编辑对象:

enter image description here

但仍然得到同样的东西..

编辑:这是来自designer.cs的datagridview的主要内容:

// 
        // dataGridView1
        // 
        this.dataGridView1.AllowUserToOrderColumns = true;
        dataGridViewCellStyle1.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleCenter;
        this.dataGridView1.AlternatingRowsDefaultCellStyle = dataGridViewCellStyle1;
        this.dataGridView1.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
        this.dataGridView1.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] {
        this.id,
        this.forage_id,
        this.caisse_id,
        this.unite_cotes,
        this.cote_tete,
        this.cote_pieds,
        this.systemes,
        this.epoque,
        this.formations,
        this.storage,
        this.categorie,
        this.status,
        this.remarques,
        this.nb_caisses});
        this.dataGridView1.Location = new System.Drawing.Point(6, 19);
        this.dataGridView1.Name = "dataGridView1";
        this.dataGridView1.Size = new System.Drawing.Size(1120, 349);
        this.dataGridView1.TabIndex = 0;
        // 

2 个答案:

答案 0 :(得分:0)

以编程方式设置每列的对齐方式: -

this.dataGridView1.Columns[column-name].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;

答案 1 :(得分:0)

您似乎只为交替的行设置样式,而不是DefaultCellStyle。看看我编写的这段代码来测试你的问题。

    dataGridView1.AllowUserToOrderColumns = true;
    DataGridViewCellStyle cellStyle = new DataGridViewCellStyle();
    cellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;

    // Replace this
    //dataGridView1.AlternatingRowsDefaultCellStyle = cellStyle;
    // With this
    dataGridView1.DefaultCellStyle = cellStyle;

    dataGridView1.Columns.Add(new DataGridViewTextBoxColumn());
    dataGridView1.Columns.Add(new DataGridViewTextBoxColumn());
    dataGridView1.Columns.Add(new DataGridViewTextBoxColumn());
    dataGridView1.Columns.Add(new DataGridViewTextBoxColumn());

    for (int i = 0; i < 10; i++)
    {
        dataGridView1.Rows.Add(1, "Test", 14, "Long String With Spaces");
    }