2012-03-18 34 views
3

通过关闭页面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(); 

    } 


} 

回答

2

的“的ExecuteReader”返回复杂/非标量值。使用“ExecuteScalar”的方法来代替:

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

我得到一个错误,说我已经有一个DataReader开放,associ以指挥。这是什么意思? – Joel 2012-03-18 19:55:12

+0

确定使用此代码并通过关闭第init页上的连接然后重新打开。谢谢! – Joel 2012-03-18 20:06:12

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(); 
} 
-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(); 
} 

无需代码手动关闭连接

0

如果我们打算从表中取一个值。然后我们可以去执行标量,而不是数据适配器或数据读取器..

方法1:

fNameTextBox.Text = command.ExecuteScalar().ToString(); 

方法2:(如果你使用任何常用的功能)

object scalarobject; 
    scalarobject = command.ExecuteScalar(); 
fNameTextBox.Text = scalarobject.ToString();