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 selecte
Solution 1:
Try modifying the code this way:
stringsqlquery="SELECT FirstName FROM ContactPerson WHERE Contact_ID = " + fNameTemp;
SqlCommandcommand=newSqlCommand(sqlquery, connection);
SqlDataReadersdr= command.ExecuteReader();
while ( sdr.Read() )
{
fNameTextBox.Text = sdr[ "FirstName" ].ToString();
}
Solution 2:
The “ExecuteReader” returns complex/non-scalar value. Use the “ExecuteScalar” method instead:
SqlCommandcommand=newSqlCommand(sqlquery, connection);
fNameTextBox.Text = command.ExecuteScalar().ToString();
Solution 3:
If we are going to fetch a single value from a table.. Then we can go for execute scalar instead of data adapter or data reader..
Method 1:
fNameTextBox.Text = command.ExecuteScalar().ToString();Method 2:(If you use any common function)
object scalarobject;
scalarobject = command.ExecuteScalar();
fNameTextBox.Text = scalarobject.ToString();
Solution 4:
There is several way to achieve this, close the connection by hardcode was not the best practice instead of using connection.close() you can place the connection inside using tag, this your code with using tag
using (SqlConnectionconnection=newSqlConnection("SqlConnection"))
{
connection.Open();
SqlCommandSqlCommandDD=newSqlCommand("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
Post a Comment for "Get Data From Sql Query Into Textbox"