通过在init页面关闭连接然后在Dropdownlist重新打开来修复它。
我已经搜索了这个问题的答案,但没有任何运气。
我想从选定的下拉列表项中获取数据到文本框。我一直试图执行这个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();
}
}
答案 0 :(得分:2)
“ExecuteReader”返回复数/非标量值。改为使用“ExecuteScalar”方法:
SqlCommand command = new SqlCommand(sqlquery, connection);
fNameTextBox.Text = command.ExecuteScalar().ToString();
答案 1 :(得分:2)
尝试以这种方式修改代码:
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();
}
答案 2 :(得分:0)
如果我们要从表中获取单个值..那么我们可以使用执行标量而不是数据适配器或数据读取器..
方法1:
fNameTextBox.Text = command.ExecuteScalar().ToString();
方法2 :(如果使用任何常用功能)
object scalarobject;
scalarobject = command.ExecuteScalar();
fNameTextBox.Text = scalarobject.ToString();
答案 3 :(得分:-1)
有几种方法可以实现这一点,通过硬编码关闭连接不是最好的做法,而不是使用connection.close()你可以使用标签放置连接,这是你的代码使用标签
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();
}
无需手动关闭连接