通过关闭页面init处的连接并在Dropdownlist中重新打开来修复它。从sql查询获取数据到文本框
我已经搜索了这个问题的答案,但没有任何运气。
我想从选定的下拉列表项目获取数据到文本框。我一直在试图执行这个SQL查询没有任何成功。
这里是我的代码:
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();
}
}
我得到一个错误,说我已经有一个DataReader开放,associ以指挥。这是什么意思? – Joel 2012-03-18 19:55:12
确定使用此代码并通过关闭第init页上的连接然后重新打开。谢谢! – Joel 2012-03-18 20:06:12