根据DropDownList的选择填充几个TextBox

时间:2012-08-31 14:06:58

标签: asp.net drop-down-menu

我从数据库填充了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"));
}

1 个答案:

答案 0 :(得分: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();
  }