C# 使用列表填充和使用自动生成字段时无法更改列名
默认的列名是item1、item2和item3,我无法更改它们,我在这里看到了一个类似的问题,但没有一个解决方案有效C# 使用列表填充和使用自动生成字段时无法更改列名,c#,asp.net,gridview,C#,Asp.net,Gridview,默认的列名是item1、item2和item3,我无法更改它们,我在这里看到了一个类似的问题,但没有一个解决方案有效 if (depositTotal != cartTotal & depositTotal != 0.0) { list.Add(Tuple.Create(amazonOrderID, depositTotal, cartTotal)); } dataGridTotals.DataSource = list; dataGridTotals
if (depositTotal != cartTotal & depositTotal != 0.0)
{
list.Add(Tuple.Create(amazonOrderID, depositTotal, cartTotal));
}
dataGridTotals.DataSource = list;
dataGridTotals.DataBind();
在绑定gridview数据之前和之后,我都尝试过使用此选项,但不起作用:
dataGridTotals.Columns[0].HeaderText = "New Header for Column";
有人有其他想法吗?自动生成的列不填充列列表。您需要循环第一行的单元格控件并手动更改文本 将此方法用于网格的
RowDataBound
事件。它将捕获标题行并重新分配文本值。此代码假定您知道接收列的顺序。如果没有,你可以阅读每一行的文字,并采取相应的行动
private void gvMyGrid_RowDataBound(object sender, GridViewRowEventArgs e)
{
// Apply to header only.
if (e.Row.RowType == DataControlRowType.Header)
{
e.Row.Cells[0].Text = "Column 1 Text";
e.Row.Cells[1].Text = "Column 2 Text";
e.Row.Cells[2].Text = "Column 3 Text";
}
}
以上代码假定您知道接收列的顺序。如果没有,您可以阅读每行的文本并采取相应的行动:
private void gvMyGrid_RowDataBound(object sender, GridViewRowEventArgs e)
{
// Apply to header only.
if (e.Row.RowType == DataControlRowType.Header)
{
foreach (Cell cell in e.Row.Cells)
{
if (cell.Text == "FName")
{
cell.Text = "First Name";
}
else if (cell.Text == "LName")
{
cell.Text = "Last Name";
}
else if (cell.Text == "Etc")
{
cell.Text = "Et cetera";
}
}
}
}
在后一种情况下,您需要设置一个SQL字段名和友好的英文名称字典来阅读,这样您就不会有50条
if
语句,但您知道了。请不要在标题前面加上“C#Gridview”之类的前缀。这就是标记的用途。自动生成的列不会填充列列表。你需要在第一行的单元格控件中循环并手动更改文本。看看Marc Gravell的方法:@John:前缀/后缀技术总是很糟糕吗?当一个问题的标题是Group with LINQ
而不是Group with SQL Server
@Justin Satyt时,这会有所不同(并且更好地搜索),那么你能给我指出正确的方向吗?谢谢你,我已经使用displayname属性解决了这个问题,不过,我明天会尝试这个解决方案。如果您决定需要使任何列不可见、更改其宽度等,这个方法实际上会派上用场。