【问题标题】:How to setup caption for DataGridView如何为 DataGridView 设置标题
【发布时间】:2009-05-22 14:50:37
【问题描述】:

我在 WinForm 应用程序中使用 DataGridView 来显示数据表。除了 DataColumn 的 Caption 属性外,一切正常。我尝试设置 Caption 属性,但似乎 DataGridView 使用 DataColumn 的名称作为标题而不是 Caption 属性的值?

对此有谷歌,似乎这个标题属性是故意禁用的。

我的 WinForm 应用程序是本地化的,我需要用中文显示标题。有谁知道我该怎么做?

这是我设置数据表的代码

// Create a new DataTable.
DataTable table = new DataTable("Payments");

// Declare variables for DataColumn and DataRow objects.
DataColumn column;
DataRow row;

// Create new DataColumn, set DataType, 
// ColumnName and add to DataTable.    
column = new DataColumn();
column.DataType = System.Type.GetType("System.Int32");
column.ColumnName = "id";
column.ReadOnly = true;
column.Unique = true;
column.Caption = LocalizedCaption.get("id") //LocalizedCaption is my library to retrieve the chinese caption

// Add the Column to the DataColumnCollection.
table.Columns.Add(column);


// Create three new DataRow objects and add them to the DataTable
for (int i = 0; i <= 2; i++)
{
    row = table.NewRow();
    row["id"] = i;
    table.Rows.Add(row);
}

//assign the DataTable as the datasource for a DataGridView
dataGridView1.DataSource = table;

【问题讨论】:

    标签: c# winforms datagridview internationalization


    【解决方案1】:

    您有几个选择。这是一个应该有效的快速修复,只需将其添加到代码块的末尾即可:

            //Copy column captions into DataGridView
            for (int i = 0; i < table.Columns.Count; i++) {
                if (dataGridView1.Columns.Count >= i) {
                    dataGridView1.Columns[i].HeaderText = table.Columns[i].Caption;
                }
            }
    

    如您所见,这只是将您现有的列标题复制到每个 DataGridView 列的正确 HeaderText 属性中。这假定在您绑定 DataTable 之前,DataGridView 中不存在以前的列。

    【讨论】:

      【解决方案2】:

      这对我有用:

      private void DataGrid_AutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e)
      {
          var dGrid = (sender as DataGrid);
          if (dGrid == null) return ;
          var view = dGrid.ItemsSource as DataView;
          if (view == null) return;
          var table = view.Table;
          e.Column.Header = table.Columns[e.Column.Header as String].Caption;
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2010-11-05
        • 1970-01-01
        • 2012-03-16
        • 2015-04-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多