Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/extjs/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 设置具有对象数据源的DataGridView中自动生成列的格式_C#_Winforms_Datagridview_.net 2.0 - Fatal编程技术网

C# 设置具有对象数据源的DataGridView中自动生成列的格式

C# 设置具有对象数据源的DataGridView中自动生成列的格式,c#,winforms,datagridview,.net-2.0,C#,Winforms,Datagridview,.net 2.0,我想根据自定义类自动创建DataGridView的所有列。每件事都像它应该的那样工作,但我需要的是格式化和对齐单元格值 因此,是否有一个属性,我可以添加到我的字段高度表,以便它可以根据需要对齐和格式化。要在手动列“创建代码”中执行此操作,您将使用以下命令: DataGridViewColumn.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight; DataGridViewColumn.DefaultCellS

我想根据自定义类自动创建DataGridView的所有列。每件事都像它应该的那样工作,但我需要的是格式化和对齐单元格值

因此,是否有一个属性,我可以添加到我的字段高度表,以便它可以根据需要对齐和格式化。要在手动列“创建代码”中执行此操作,您将使用以下命令:

DataGridViewColumn.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
DataGridViewColumn.DefaultCellStyle.Format = "N2";
如何在使用AutoGenerateColumns解决方案时指定DefaultCellStyle属性-注意,我仅限于使用.net 2:

以下是我所需要和得到的示例:

public partial class Form1 : Form
{
  private List<Person> people = new List<Person>();
  private DataGridView dataGridView1 = new DataGridView();
  private DataGridView dataGridView2 = new DataGridView();
  public Form1()
  {
    InitializeComponent();
    dataGridView1.Dock = DockStyle.Top;
    dataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells;

    dataGridView2.Dock = DockStyle.Top;
    dataGridView2.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells;

    Controls.Add(dataGridView2);
    Controls.Add(dataGridView1);

    Load += new EventHandler(Form1_Load);
    Text = "";
  }

  private void Form1_Load(object sender, EventArgs e)
  {
    PopulateLists();
    dataGridView1.AutoGenerateColumns = true;
    dataGridView1.DataSource = people;

    CreateAndPopulateGrid2();
  }

  public void CreateAndPopulateGrid2()
  {
    DataGridViewColumn columnName = new DataGridViewTextBoxColumn();
    columnName.HeaderText = "Name";

    DataGridViewColumn columnHeight = new DataGridViewTextBoxColumn();
    columnHeight.HeaderText = "Height [m]";
    columnHeight.ValueType = typeof(double);

    columnHeight.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
    columnHeight.DefaultCellStyle.Format = "N2";
    dataGridView2.Rows.Clear();
    dataGridView2.Columns.Clear();
    dataGridView2.Columns.Add(columnName);
    dataGridView2.Columns.Add(columnHeight);

    DataGridViewRow row;
    foreach (Person p in people)
    {
      row = new DataGridViewRow();
      row.CreateCells(dataGridView2);
      row.Cells[0].Value = p.Name;
      row.Cells[1].Value = p.HeightMeter;
      dataGridView2.Rows.Add(row);
    }
  }

  private void PopulateLists()
  {
    people.Clear();
    people.Add(new Person("Harry", 1.7523));
    people.Add(new Person("Sally", 1.658));
    people.Add(new Person("Roy", 2.158));
    people.Add(new Person("Pris", 1.2584));
  }
}

class Person
{
  [System.ComponentModel.DisplayName("Name")]
  public string Name { get; set; }
  [System.ComponentModel.DisplayName("Height [m]")]
  public double HeightMeter { get; set; }

  public Person(string name, double heightMeter)
  {
    Name = name;
    HeightMeter = heightMeter;
  }
}
使用自定义属性控制DataGridView列的外观 在DataGridView中自动生成列时,内置了对一些属性的支持,包括ReadOnly、DisplayName和Browsable属性。例如,如果使用Browsablefalse标记属性,则不会将其作为列添加到DataGridView

但对于格式,没有这样的内置支持。您可以创建一个自定义DisplayFormat属性,并在自动生成列后编写一些代码在DataGridView中使用它

例如,假设您有这样一个类:

using System;
using System.ComponentModel;
public class Product
{
    [DisplayName("Code")]
    [Description("Unique code of the product")]
    public int Id { get; set; }

    [DisplayName("Product Name")]
    [Description("Name of the product")]
    public string Name { get; set; }

    [DisplayName("Unit Price")]
    [Description("Unit price of the product")]
    [DisplayFormat("C2")]
    public double Price { get; set; }
}
foreach (DataGridViewColumn c in dataGridView1.Columns)
{
    if (c.ValueType == typeof(double))
    {
        c.DefaultCellStyle.Format = "C2";
        c.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
    }
}
因此,我们将有一个类似于屏幕截图的DataGridView,它可以看到我们使用Description属性的值作为列的工具提示文本,还使用DisplayFormat以货币格式显示价格:

首先,我们应该为format、DisplayFormat创建自定义属性:

然后加载数据并自动生成列,例如:

var list = new List<Product>() {
    new Product(){ Id=1, Name="Product 1", Price= 321.1234},
    new Product(){ Id=2, Name="Product 2", Price= 987.5678},
};
this.dataGridView1.DataSource = list;
您可以简单地将上述代码封装在类似void SetupColumnDataGridView dgv的方法中,或者如果您有派生的DataGridView,则可以创建DataBinObject数据方法,并在该方法中,将数据分配给DataSource,然后将上述代码用作该方法主体的其余部分

我也在你的问题下面的评论中读到,你告诉我,“…每个字段都有点多。”如果出于任何原因你不喜欢属性方法,你可以简单地坚持这样的for循环:

using System;
using System.ComponentModel;
public class Product
{
    [DisplayName("Code")]
    [Description("Unique code of the product")]
    public int Id { get; set; }

    [DisplayName("Product Name")]
    [Description("Name of the product")]
    public string Name { get; set; }

    [DisplayName("Unit Price")]
    [Description("Unit price of the product")]
    [DisplayFormat("C2")]
    public double Price { get; set; }
}
foreach (DataGridViewColumn c in dataGridView1.Columns)
{
    if (c.ValueType == typeof(double))
    {
        c.DefaultCellStyle.Format = "C2";
        c.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
    }
}
Windows窗体中属性的DataAnnotations 要了解如何将Windows窗体中的数据批注属性用于DataGridView和验证,请参阅以下文章:


我想从类生成DataGridView列。我需要的是在某些列上应用格式。这可以在使用DefaultCellStyle属性手动创建列时完成。但我需要这样定义,就像我用属性或任何不强迫我手动创建每个列的方式来定义列的名称一样。在自动生成列之后,无论您在何处设置网格,您都可以创建一些自定义属性并用这些属性装饰属性,您可以编写一些代码从这些属性中提取元数据并应用于网格。另一个选项是,您可以让datagridview自动生成列。然后编写一些代码来手动设置列。例如dgv.Columns[Id].Width=200;等等。谢谢,这确实是一个选项,但是有没有一个内置的方式让我不必创建自己的属性?与使用[System.ComponentModel.DisplayNameName]设置列的标题文本一样,是否无法以相同的方式访问DefaultCellStyle?如果没有任何人知道的方法,我将创建自己的属性来访问这些属性。没有内置的方法。请确保阅读答案的编辑版本。我将代码更改为.NET2。代码的第一个版本是在.NET的更高版本中编写的。非常感谢。我喜欢属性方法是的。这将非常有效,因为并非所有的双字段都具有相同的格式。对于某些字段,我需要比其他字段更多的小数点。将实施上述解决方案。非常感谢你。