为什么DataColumn.Caption不起作用?不起作用、DataColumn、Caption

2023-09-03 02:26:24 作者:撩人.

我想创建一个DataTable并将其绑定到一个DataGridView。它的工作原理,但我无法通过标题属性设置列标题。它显示使用的ColumnName(城市),而不是头部。 MSDN 说:您可以使用Caption属性来显示描述或友好名称的DataColumn。

 的DataColumn DC =新的DataColumn(城的typeof(字符串));
            dc.Caption =Город;

            数据表DT =新的DataTable();
            dt.Columns.Add(直流);

            DataRow的行= dt.NewRow();
            行[城市] =莫斯科;
            dt.Rows.Add(行);

            datagridview.DataSource = DT;
 

解决方案

嗯,MSDN是正确的。这是标题属性是什么。然而,这并不意味着控制制造商必须使用标题属性。在这种情况下,微软并没有做到这一点(虽然他们真的应该有)。您可以修改您的code到这虽然:

  /// SNIP

dataGridView1.DataSource = DT;

的foreach(COL的DataGridViewColumn在dataGridView1.Columns){
  col.HeaderText = dt.Columns [col.HeaderText] .Caption;
}
 

这个预训练不简单 BLIP 统一视觉 语言理解和生成任务

I am trying to create a DataTable and bind it to a DataGridView. It works, but I can't set columns headers via the Caption property. It displays headers using the ColumnName ("City") instead. MSDN says that "You can use the Caption property to display a descriptive or friendly name for a DataColumn."

            DataColumn dc = new DataColumn("City", typeof(string));
            dc.Caption = "Город"; 

            DataTable dt = new DataTable();
            dt.Columns.Add(dc); 

            DataRow row = dt.NewRow(); 
            row["City"] = "Moscow";
            dt.Rows.Add(row);

            datagridview.DataSource = dt;

解决方案

Well, MSDN is right. That is what the Caption property is for. However, that doesn't mean that control makers have to use the caption property. In this case, Microsoft didn't do that (although they really should have). You can modify your code to this though:

///snip

dataGridView1.DataSource = dt;

foreach (DataGridViewColumn col in dataGridView1.Columns) {
  col.HeaderText = dt.Columns[col.HeaderText].Caption;
}