Joel Joel - 2 months ago 21
SQL Question

Get data from sql query into textbox

Fixed it by closing the connetion at page init and then reopen at Dropdownlist.

I've searched for an answer to this question but without any luck.

I want to get data from a selected dropdownlist item to a textbox. I've been trying to execute this sql query without any 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();

}


}

Answer

The “ExecuteReader” returns complex/non-scalar value. Use the “ExecuteScalar” method instead:

SqlCommand command = new SqlCommand(sqlquery, connection);
fNameTextBox.Text = command.ExecuteScalar().ToString();
Comments