0

DropDownList从数据库中填充了一个。

当我在 中选择一个项目时DropDownList,我想调用一个过程并将 DropDownList 的值传递给调用过程以查询数据库以填充几个文本框。

这该怎么做?

程序代码:

protected void PopulateTextBoxes()
{
    SqlDataReader MyReader;
    SqlConnection Conn;
    SqlParameter TourIdParam;

    string strConnection = ConfigurationManager.ConnectionStrings["ChinatowndbConnString"].ConnectionString;

    Conn = new SqlConnection(strConnection);

    SqlCommand MyCommand = new SqlCommand();

    MyCommand.CommandText = "SELECT TourId, TName, TDetails FROM Chinatowndb.dbo.Tour Where TourId = @TourIdp";
    MyCommand.CommandType = CommandType.Text;
    MyCommand.Connection = Conn;

    TourIdParam = new SqlParameter();
    TourIdParam.ParameterName = "@TourIdp";
    TourIdParam.SqlDbType = SqlDbType.Int;
    TourIdParam.Direction = ParameterDirection.Input;
    TourIdParam.Value = ddlTour.SelectedItem.Value;

    MyCommand.Parameters.Add(TourIdParam);

    MyCommand.Connection.Open();
    MyReader = MyCommand.ExecuteReader(CommandBehavior.CloseConnection);

    while (MyReader.Read())
    {
        tbTourName.Text = (string)MyReader["TName"];
        tbTourDetails.Text = (string)MyReader["TDetails"];
        lblTourId.Text = Convert.ToString(MyReader["TourId"]);
    }
}

要填充的代码DropDownBox

private void PopulateTour()
{

    DataTable dtTour = new DataTable();

    string strConnection = ConfigurationManager.ConnectionStrings["ChinatowndbConnString"].ConnectionString;

    using (SqlConnection con = new SqlConnection(strConnection))
    {

        try
        {
            SqlDataAdapter adapter = new SqlDataAdapter("SELECT TourId, TName FROM Chinatowndb.dbo.Tour", con);
            adapter.Fill(dtTour);

            ddlTour.DataSource = dtTour;
            ddlTour.DataValueField = "TourId";
            ddlTour.DataTextField = "TName";
            ddlTour.DataBind();
        }
        catch (Exception ex)
        {
            // Handle the error
        }

    }

    // Add the initial item
    ddlTour.Items.Insert(0, new ListItem("<Select Tour>", "0"));
}
4

1 回答 1

0

您需要为 HTML 中的选择更改添加事件处理程序

<asp:DropDownList id="ddlTour"
     AutoPostBack="True"
     OnSelectedIndexChanged="ddlTour_SelectedIndexChanged"
     runat="server">

并在您的代码中处理事件

  void ddlTour_SelectedIndexChanged(Object sender, EventArgs e)
  {
        // Call the method that gets the current item from the dropdown and fills the textboxes
        PopulateTextBoxes();
  }
于 2012-08-31T14:14:34.290 回答