Hi asolmdu,
I have Created a sample please take its reference and correct your code.
Database
For this example I have used of Northwind database that you can download using the link given below.
Download Northwind Database
HTML
<asp:GridView runat="server" ID="gvOrders" AutoGenerateColumns="false" OnRowDataBound="RowDataBound">
<Columns>
<asp:TemplateField HeaderText="Order ID">
<ItemTemplate>
<asp:Label ID="lblID" Text='<%# Eval("OrderID") %>' runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Price">
<ItemTemplate>
<asp:Label ID="lblPrice" Text='<%# Eval("Freight") %>' runat="server" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
NameSpaces
C#
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Web.UI;
VB.Net
Imports System.Configuration
Imports System.Data
Imports System.Data.SqlClient
Imports System.Web.UI
Code
C#
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["constr"].ConnectionString))
{
using (SqlCommand cmd = new SqlCommand("SELECT TOP 5 OrderID,Freight FROM Orders", con))
{
cmd.CommandType = CommandType.Text;
using (SqlDataAdapter sda = new SqlDataAdapter())
{
sda.SelectCommand = cmd;
DataTable dt = new DataTable();
sda.Fill(dt);
this.gvOrders.DataSource = dt;
this.gvOrders.DataBind();
}
}
}
}
}
protected void RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
(e.Row.FindControl("lblPrice") as Label).Text = string.Format("{0:N2}", Convert.ToDecimal(DataBinder.Eval(e.Row.DataItem, "Freight").ToString()));
}
}
VB.Net
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
If Not Me.IsPostBack Then
Using con As SqlConnection = New SqlConnection(ConfigurationManager.ConnectionStrings("constr").ConnectionString)
Using cmd As SqlCommand = New SqlCommand("SELECT TOP 5 OrderID,Freight FROM Orders", con)
cmd.CommandType = CommandType.Text
Using sda As SqlDataAdapter = New SqlDataAdapter()
sda.SelectCommand = cmd
Dim dt As DataTable = New DataTable()
sda.Fill(dt)
Me.gvOrders.DataSource = dt
Me.gvOrders.DataBind()
End Using
End Using
End Using
End If
End Sub
Protected Sub RowDataBound(ByVal sender As Object, ByVal e As GridViewRowEventArgs)
If e.Row.RowType = DataControlRowType.DataRow Then
TryCast(e.Row.FindControl("lblPrice"), Label).Text = String.Format("{0:N2}", Convert.ToDecimal(DataBinder.Eval(e.Row.DataItem, "Freight").ToString()))
End If
End Sub
Screenshot
