If you use the DataColumn.Caption property to set the display text for column headers of a DataGrid Web server control, the column headers may not be set to the text
that you specify.
↑ Back to the top
Columns are abstracted as properties of a DataRow object. By design, the properties are named according to the
value of the ColumnName property, not the value of the Caption property so that you can bind to arbitrary objects and not just
to DataRow objects.
↑ Back to the top
To set the header text for columns so that the text differs
from the value of the ColumnName, set the AutoGenerateColumns property to false. Additionally, you must explicitly declare the column and specify
the header text for the column.
↑ Back to the top
Steps to Reproduce the Behavior
- Create a new ASP.NET Web application in Microsoft Visual
Basic .NET or Microsoft Visual C# .NET.
- Add a Web Form to your project.
- Add the following code to the Web Form:
<%@ import namespace=System.Data %>
<%@ Page language="c#" %>
<HTML>
<HEAD>
<script runat="server">
void Page_Load(Object sender, EventArgs e) {
//Create a DataTable.
DataTable myTable = new DataTable("myTable");
// Create a DataColumn, and set various properties.
DataColumn dc = new DataColumn();
dc.DataType = System.Type.GetType("System.Decimal");
dc.AllowDBNull = false;
dc.Caption = "Price";
dc.ColumnName = "Price_Test";
dc.DefaultValue = 25;
// Add the column to the table.
myTable.Columns.Add(dc);
// Add ten rows, and then set their values.
DataRow myRow;
for(int i = 0; i < 10; i++)
{
myRow = myTable.NewRow();
myRow["Price_Test"] = i + 1;
//Be sure to add the new row to the DataRowCollection.
myTable.Rows.Add(myRow);
}
DataSet myDataSet = new DataSet();
//Add the new DataTable to the DataSet.
myDataSet.Tables.Add(myTable);
MyGrid.DataSource = myDataSet.Tables[0].DefaultView;
MyGrid.DataBind();
}
</script>
</HEAD>
<body>
<form method="post" runat="server">
<asp:datagrid id="MyGrid" runat="Server" />
</form>
</body>
</HTML>
- Save the Web Form.
- View the page in the browser. Notice that the HeaderText property is set to Price_Test (the value of the ColumnName) instead of the caption (Price) that you specified.
To resolve this problem, replace the code in this sample
<form method="post" runat="server">
<asp:datagrid id="MyGrid" runat="Server" />
</form>
with the following code:
<form method="post" runat="server" ID="Form1">
<asp:datagrid id="MyGrid" AutoGenerateColumns = "false" runat="Server">
<Columns>
<asp:BoundColumn HeaderText="Price" DataField="Price_Test"></asp:BoundColumn>
</Columns>
</asp:DataGrid>
</form>
↑ Back to the top
For additional information about the ASP.NET roadmap, click
the article number below to view the article in the Microsoft Knowledge Base:
For general information about ASP.NET, see the following MSDN
newsgroup:
↑ Back to the top