Introduction:
In the Sample code we'll see how to change the Datagrid HeaderText.
Solution 1:
Set the Property AutoGenerateColumns=False of the Datagrid and with the BoundColumn give the Appropriate HeaderText
<asp:DataGrid id="DataGrid1" AutoGenerateColumns="False" runat="server">
<Columns>
<asp:BoundColumn DataField="EmployeeID" HeaderText="Employee ID">
</asp:BoundColumn>
<asp:BoundColumn DataField="FirstName" HeaderText="First Name">
</asp:BoundColumn>
<asp:BoundColumn DataField="LastName" HeaderText="Last Name">
</asp:BoundColumn>
</Columns>
</asp:DataGrid>
Solution 2:
Drag drop DataGrid.
<asp:DataGrid id="DataGrid1" runat="server"></asp:DataGrid>
Now to display the HeaderText through the code-behind.
Private Sub DataGrid1_ItemDataBound(ByVal sender As Object, _ByVal e As System.Web.UI.WebControls.DataGridItemEventArgs) Handles DataGrid1.ItemDataBound
If e.Item.ItemType = ListItemType.Header Then
e.Item.Cells(0).Text = "Employee ID"
e.Item.Cells(1).Text = "First Name"
e.Item.Cells(2).Text = "Last Name"
End If
End Sub
Common Code: (For Solution 1 and 2)
To bind the Data to Datagrid we have used a DataReader for this Sample.
Dim myquery As String
Dim myconnection As SqlConnection
Dim mycmd As SqlCommand
Dim myreader As SqlDataReader
Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
'Put user code to initialize the page here
myconnection = New SqlConnection("server=localhost;uid=sa;pwd=;database=northwind")
myquery = "select Employeeid, FirstName,LastName from employees where employeeid<4"
mycmd = New SqlCommand(myquery, myconnection)
myconnection.Open()
myreader = mycmd.ExecuteReader(CommandBehavior.CloseConnection)
DataGrid1.DataSource = myreader
DataGrid1.DataBind()
myreader.Close()
myconnection.Close()
End Sub