Get data from SQL query into textbox
Fixed it by closing the connection in the init page and then reopening it in the dropdown.
I've been looking for an answer to this question, but with no luck.
I want to get data from a selected dropdownlist item into a textbox. I tried to execute this SQL query with no success.
Here's my code:
public partial class EditContact : System.Web.UI.Page
{
SqlConnection connection = new SqlConnection("SqlConnection");
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Page_Init(object sender, EventArgs e)
{
connection.Open();
SqlCommand SqlCommandDD = new SqlCommand("SELECT FirstName + ' ' + LastName AS 'TextField', Contact_ID, Email, PhoneNumber, CompanyID FROM ContactPerson");
SqlCommandDD.Connection = connection;
DropDownList2.DataSource = SqlCommandDD.ExecuteReader();
DropDownList2.DataValueField = "Contact_ID";
DropDownList2.DataTextField = "TextField";
DropDownList2.DataBind();
}
protected void DropDownList2_SelectedIndexChanged(object sender, EventArgs e)
{
string fNameTemp = DropDownList2.SelectedValue;
string sqlquery = ("SELECT FirstName FROM ContactPerson WHERE (Contact_ID = " + fNameTemp + ")");
SqlCommand command = new SqlCommand(sqlquery, connection);
SqlDataReader sdr = command.ExecuteReader();
fNameTextBox.Text = sdr.ToString();
}
}
source to share
"ExecuteReader" returns a complex / non-scalar value. Use ExecuteScalar " instead :
SqlCommand command = new SqlCommand(sqlquery, connection);
fNameTextBox.Text = command.ExecuteScalar().ToString();
source to share
Try changing your code like this:
string sqlquery = "SELECT FirstName FROM ContactPerson WHERE Contact_ID = " + fNameTemp;
SqlCommand command = new SqlCommand(sqlquery, connection);
SqlDataReader sdr = command.ExecuteReader();
while ( sdr.Read() )
{
fNameTextBox.Text = sdr[ "FirstName" ].ToString();
}
source to share
If we are going to retrieve one value from a table .. Then we can go for executing a scalar instead of a data adapter or reading data.
Method 1:
fNameTextBox.Text = command.ExecuteScalar().ToString();
Method 2: (If you are using any generic function)
object scalarobject;
scalarobject = command.ExecuteScalar();
fNameTextBox.Text = scalarobject.ToString();
source to share
There are several ways to achieve this, close the connection with hard code was not best practice instead of using connection.close () you can put the connection inside with a tag, this code with a tag
using (SqlConnection connection = new SqlConnection("SqlConnection"))
{
connection.Open();
SqlCommand SqlCommandDD = new SqlCommand("SELECT FirstName + ' ' + LastName AS 'TextField', Contact_ID, Email, PhoneNumber, CompanyID FROM ContactPerson");
SqlCommandDD.Connection = connection;
DropDownList2.DataSource = SqlCommandDD.ExecuteReader();
DropDownList2.DataValueField = "Contact_ID";
DropDownList2.DataTextField = "TextField";
DropDownList2.DataBind();
}
no need to close the connection manually
source to share