Hi david.ee,
Please take reference the below code and correct your code.
Database
For this sample I have used of NorthWind database that you can download using the link given below.
Download Northwind Database
HTML
<asp:GridView ID="gvCustomers" runat="server" AutoGenerateColumns="False">
<Columns>
<asp:TemplateField HeaderText="ContactName" Visible="False">
<ItemTemplate>
<asp:Label ID="lblContactName" runat="server" Text='<%# Eval("ContactName") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="CustomerID">
<ItemTemplate>
<asp:Label ID="lblCustomerID" runat="server" Text='<%# Eval("CustomerID") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="City">
<ItemTemplate>
<asp:Label ID="lblCity" runat="server" Text='<%# Eval("City") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Country">
<ItemTemplate>
<asp:Label ID="lblCountry" runat="server" Text='<%# Eval("Country") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<br />
<asp:TextBox ID="txtCustomerIds" runat="server" Width="300px"></asp:TextBox>
Namespaces
C#
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
VB.Net
Imports System.Data.SqlClient
Imports System.Data
Code
C#
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
string constr = ConfigurationManager.ConnectionStrings["Constring"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("SELECT TOP 5 CustomerID,ContactName,City,Country FROM Customers", con))
{
using (SqlDataAdapter da = new SqlDataAdapter(cmd))
{
using (DataTable dt = new DataTable())
{
da.Fill(dt);
this.gvCustomers.DataSource = dt;
this.gvCustomers.DataBind();
for (int i = 0; i < this.gvCustomers.Rows.Count; i++)
{
this.txtCustomerIds.Text += (this.gvCustomers.Rows[i].FindControl("lblCustomerID") as Label).Text + " ";
}
}
}
}
}
}
}
Vb.Net
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
If Not Me.IsPostBack Then
Dim constr As String = ConfigurationManager.ConnectionStrings("Constring").ConnectionString
Using con As SqlConnection = New SqlConnection(constr)
Using cmd As SqlCommand = New SqlCommand("SELECT TOP 5 CustomerID,ContactName,City,Country FROM Customers", con)
Using da As SqlDataAdapter = New SqlDataAdapter(cmd)
Using dt As DataTable = New DataTable()
da.Fill(dt)
Me.gvCustomers.DataSource = dt
Me.gvCustomers.DataBind()
For i As Integer = 0 To Me.gvCustomers.Rows.Count - 1
Me.txtCustomerIds.Text += (TryCast(Me.gvCustomers.Rows(i).FindControl("lblCustomerID"), Label)).Text & " "
Next
End Using
End Using
End Using
End Using
End If
End Sub
Screenshot
