Hi trisetia302,
Use ExecuteScalar of SqlCommand class.
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:ScriptManager runat="server" />
<asp:TextBox ID="txtId" runat="server" placeholder="Enter ID"></asp:TextBox>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:Button ID="btnGet" runat="server" Text="Get" OnClick="OnGet" />
</ContentTemplate>
</asp:UpdatePanel>
<asp:TextBox ID="txtName" runat="server" placeholder="Enter Name" ReadOnly="true"></asp:TextBox>
Namespaces
C#
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
VB.Net
Imports System.Configuration
Imports System.Data
Imports System.Data.SqlClient
Code
C#
protected void OnGet(object sender, EventArgs e)
{
using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["dbcs"].ConnectionString))
{
using (SqlCommand sqlcmd = new SqlCommand())
{
sqlcmd.CommandText = "Select FirstName from Employees where EmployeeId=@Id";
sqlcmd.Parameters.AddWithValue("@Id", txtId.Text.Trim());
sqlcmd.CommandType = CommandType.Text;
sqlcmd.Connection = con;
con.Open();
string name = Convert.ToString(sqlcmd.ExecuteScalar());
ScriptManager.RegisterStartupScript(Page, this.GetType(), "id", "$get('txtName').value='" + name + "';", true);
con.Close();
}
}
}
VB.Net
Protected Sub OnGet(ByVal sender As Object, ByVal e As EventArgs)
Using con As SqlConnection = New SqlConnection(ConfigurationManager.ConnectionStrings("dbcs").ConnectionString)
Using sqlcmd As SqlCommand = New SqlCommand()
sqlcmd.CommandText = "Select FirstName from Employees where EmployeeId=@Id"
sqlcmd.Parameters.AddWithValue("@Id", txtId.Text.Trim())
sqlcmd.CommandType = CommandType.Text
sqlcmd.Connection = con
con.Open()
Dim name As String = Convert.ToString(sqlcmd.ExecuteScalar())
ScriptManager.RegisterStartupScript(Page, Me.[GetType](), "id", "$get('txtName').value='" & name & "';", True)
con.Close()
End Using
End Using
End Sub
Screenshot