我正在尝试使用droplistlist填充2个文本框 我已经在default.aspx中定义了下拉列表,如下所示:
<asp:DropDownList ID="DropDownList1" runat="server" DataSourceID="SqlDataSource1" DataTextField="Player" DataValueField="ID" AppendDataBoundItems="true" AutoPostBack="true" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged">
<asp:ListItem Value="">Please Select</asp:ListItem></asp:DropDownList>`
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:Phocas_WorkBenchConnectionString %>" SelectCommand="SELECT ID, [PlayerFirstName] + ' ' + [PlayerLastName] as 'Player' FROM [Players]"></asp:SqlDataSource>
我在default.aspx.cs中创建了C#代码,如下所示:
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
SqlConnection sql = new SqlConnection(@"Data Source=DESKTOP-PMSK135\SQLEXPRESS;Initial Catalog=Phocas_WorkBench;Integrated Security=True");
{
SqlCommand getFirstName = new SqlCommand("Select PlayerFirstName from Players where ID = @PlayerID", sql);
SqlCommand getLastName = new SqlCommand("Select PlayerLastName from Players where ID = @PlayerID", sql);
getFirstName.Parameters.AddWithValue("@PlayerID", DropDownList1.SelectedValue);
getLastName.Parameters.AddWithValue("@PlayerID", DropDownList1.SelectedValue);
TextBox3.Text = getFirstName.CommandText;
sql.Open(); //Opens Connection to the SQL Database using the definded Connection String. In this case the defined connection string is stored in "sql"
string getResults = (string)getFirstName.ExecuteScalar();
TextBox3.Text = getResults;
getResults = (string)getLastName.ExecuteScalar();
TextBox4.Text = getResults;
sql.Close();
}
}
我希望将2个SqlCommands的结果填充到textbox3和textbox4中,其中@PlayerID等于存储在下拉列表中的结果,其中DataValueField =&#34; ID&#34;因为ID是唯一标识符
谢谢
修改 我的SQL查询出错,其中&#34; WHERE&#34;声明基于名称而非ID。这是一个错误,它总是被认为是ID。
我可以确认代码仍无法使用更正的SQL查询
答案 0 :(得分:0)
对我来说,似乎你的default.aspx.cs中有一个错误的SQL语句。您应该根据ID选择播放器的名字和姓氏。您可以在1个声明中执行此操作:
SqlCommand getPlayerName = new SqlCommand("Select PlayerFirstName, PlayerLastName from Players where ID = @PlayerID", sql);
当您在下拉列表中连接名字和姓氏以显示全名时,您无法在WHERE子句中使用此连接值
答案 1 :(得分:0)
你的Sql查询应该是这个
SqlCommand getFirstName = new SqlCommand("Select PlayerFirstName from Players where Id= @PlayerID", sql);
SqlCommand getLastName = new SqlCommand("Select PlayerLastName from Players where Id= @PlayerID", sql);