Hi micah,
Check this example. Now 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:TextBox runat="server" ID="txtName" />
<asp:Button Text="Get User Name" runat="server" OnClick="btnGet" />
Namespaces
C#
using System.Configuration;
using System.Data.SqlClient;
using System.Data;
VB.Net
Imports System.Data.SqlClient
Imports System.Data
Code
C#
protected void btnGet(object sender, EventArgs e)
{
string constring = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(constring))
{
using (SqlCommand cmd = new SqlCommand("SELECT ContactName FROM Customers WHERE CustomerId = 'ALFKI'", con))
{
cmd.CommandType = CommandType.Text;
con.Open();
object o = cmd.ExecuteScalar();
if (o != null)
{
txtName.Text = o.ToString();
}
con.Close();
}
}
}
VB.Net
Protected Sub btnGet(ByVal sender As Object, ByVal e As EventArgs)
Dim constring As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
Using con As SqlConnection = New SqlConnection(constring)
Using cmd As SqlCommand = New SqlCommand("SELECT ContactName FROM Customers WHERE CustomerId = 'ALFKI'", con)
cmd.CommandType = CommandType.Text
con.Open()
Dim o As Object = cmd.ExecuteScalar()
If o IsNot Nothing Then
txtName.Text = o.ToString()
End If
con.Close()
End Using
End Using
End Sub
Screenshot
