小编典典

从SQL查询获取数据到文本框

sql

通过在页面初始化时关闭连接,然后在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();

    }


}

阅读 178

收藏
2021-03-08

共1个答案

小编典典

“ xecuteReader”返回复数/非标量值。使用`` ExecuteScalar ‘’方法代替:

SqlCommand command = new SqlCommand(sqlquery, connection);
fNameTextBox.Text = command.ExecuteScalar().ToString();
2021-03-08