Hi micah,
Please refer below sample.
HTML
<asp:GridView ID="gvCustomers" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:BoundField DataField="OrderId" HeaderText="Id" />
<asp:BoundField DataField="Freight" HeaderText="Freight" />
</Columns>
</asp:GridView>
<br />
<asp:Label ID="lblCount" runat="server" />
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)
{
DataTable dt = GetCustomerDetail();
gvCustomers.DataSource = dt;
gvCustomers.DataBind();
CountCustomerId();
}
}
private DataTable GetCustomerDetail()
{
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("SELECT OrderID, Freight FROM Orders WHERE CustomerID = 'ALFKI'", con))
{
using (SqlDataAdapter da = new SqlDataAdapter(cmd))
{
DataTable dt = new DataTable();
da.Fill(dt);
return dt;
}
}
}
}
public void CountCustomerId()
{
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("SELECT COUNT(CustomerID) as TotalCount FROM Orders WHERE CustomerID = 'ALFKI'", con))
{
con.Open();
string count = cmd.ExecuteScalar().ToString();
con.Close();
lblCount.Text = "Customer Order Count is : <b>" + count + "</b>";
}
}
}
VB.Net
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
If Not Me.IsPostBack Then
Dim dt As DataTable = GetCustomerDetail()
gvCustomers.DataSource = dt
gvCustomers.DataBind()
CountCustomerId()
End If
End Sub
Private Function GetCustomerDetail() As DataTable
Dim constr As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
Using con As SqlConnection = New SqlConnection(constr)
Using cmd As SqlCommand = New SqlCommand("SELECT OrderID, Freight FROM Orders WHERE CustomerID = 'ALFKI'", con)
Using da As SqlDataAdapter = New SqlDataAdapter(cmd)
Dim dt As DataTable = New DataTable()
da.Fill(dt)
Return dt
End Using
End Using
End Using
End Function
Public Sub CountCustomerId()
Dim constr As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
Using con As SqlConnection = New SqlConnection(constr)
Using cmd As SqlCommand = New SqlCommand("SELECT COUNT(CustomerID) as TotalCount FROM Orders WHERE CustomerID = 'ALFKI'", con)
con.Open()
Dim count As String = cmd.ExecuteScalar().ToString()
con.Close()
lblCount.Text = "Customer Order Count is : <b>" & count & "</b>"
End Using
End Using
End Sub
Screenshot