Hi sambath,
Check this example. Now please take its reference and correct your code.
Database
Here I am making use of Microsoft’s Northwind Database. You can download it from here.
Download Northwind Database
HTML
<asp:GridView ID="gvEmployees" runat="server" AutoGenerateColumns="false" OnRowDataBound="OnRowDataBound">
<Columns>
<asp:BoundField DataField="EmployeeID" HeaderText="EmployeeID" />
<asp:BoundField DataField="" HeaderText="Name" />
<asp:BoundField DataField="Country" HeaderText="Country" />
</Columns>
</asp:GridView>
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)
{
this.BindGrid();
}
}
private void BindGrid()
{
string str = ConfigurationManager.ConnectionStrings["ConString"].ConnectionString;
using (SqlConnection conn = new SqlConnection(str))
{
using (SqlCommand cmd = new SqlCommand("SELECT EmployeeID,FirstName, LastName,Country FROM Employees", conn))
{
using (SqlDataAdapter da = new SqlDataAdapter(cmd))
{
using (DataTable dt = new DataTable())
{
da.Fill(dt);
this.gvEmployees.DataSource = dt;
this.gvEmployees.DataBind();
}
}
}
}
}
protected void OnRowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Cells[1].Text = string.Format("{0} {1}", DataBinder.Eval(e.Row.DataItem, "FirstName"), DataBinder.Eval(e.Row.DataItem, "LastName"));
}
}
VB.Net
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
If Not Me.IsPostBack Then
Me.BindGrid()
End If
End Sub
Private Sub BindGrid()
Dim str As String = ConfigurationManager.ConnectionStrings("ConString").ConnectionString
Using conn As SqlConnection = New SqlConnection(str)
Using cmd As SqlCommand = New SqlCommand("SELECT EmployeeID,FirstName, LastName,Country FROM Employees", conn)
Using da As SqlDataAdapter = New SqlDataAdapter(cmd)
Using dt As DataTable = New DataTable()
da.Fill(dt)
Me.gvEmployees.DataSource = dt
Me.gvEmployees.DataBind()
End Using
End Using
End Using
End Using
End Sub
Protected Sub OnRowDataBound(ByVal sender As Object, ByVal e As GridViewRowEventArgs)
If e.Row.RowType = DataControlRowType.DataRow Then
e.Row.Cells(1).Text = String.Format("{0} {1}", DataBinder.Eval(e.Row.DataItem, "FirstName"), DataBinder.Eval(e.Row.DataItem, "LastName"))
End If
End Sub
Screenshot
