C#和ASP.NET - 使用SQL表

时间:2018-04-28 03:34:30

标签: c# sql asp.net web dropdown

我正在尝试使用网页上的dropdownlist填充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>

我在C#中创建了default.aspx.cs代码,如下所示:

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



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

我希望将SqlCommand的结果填充到textbox3textbox4,其中@PlayerID等于dropdownlist中存储的结果DataValueField="ID" 1}} ID是唯一标识符

在尝试替换AddWithValue中的变量时,我尝试了许多不同的类型。看看我在下面尝试过的那些:

  • DropDownList1.text
  • DropDownList1.DataValueField
  • DropDownList1.SelectedValue
  • DropDownList1.SelectedIndex

然而,上述情况似乎都不起作用。 向正确的方向轻推将非常有帮助

谢谢。

0 个答案:

没有答案