从ASP.Net Code-Behind获取/设置Literal中的选择框

时间:2011-08-15 21:04:30

标签: c# asp.net forms pass-by-value

我将以下代码添加到表单中的文字中。我在后面的代码中如何从select = name =“populationSelect”中获取/设置数据....?

 protected void PopulatePopulation()
{
    StringBuilder sb = new StringBuilder();
    StringBuilder sql = new StringBuilder();

    // Define sql
    sql.Append("SELECT pid, population ");
    sql.Append("FROM populations ");
    sql.Append("ORDER BY pid ASC ");

    using (IDataReader reader = SqlHelper.GetDataReader(sql.ToString()))
    {
        sb.AppendLine("<div class=\"narrowRes\">Poulation</div><select name=\"populationSelect\" class=\"narrowResSelect\"><option value=\"0\">All populations</option>");

        while (reader.Read())
        {
            int pid = reader.IsDBNull(0) ? -1 : reader.GetInt32(0);
            string population = reader.IsDBNull(1) ? string.Empty : reader.GetString(1);

            population = population.Trim();

            sb.AppendLine(string.Format("<option value=\"{0}\">{1}</option>", pid, population));
        }
    }

    sb.AppendLine("</select>");

    ltrlExplorePopulation.Text = sb.ToString();
}

1 个答案:

答案 0 :(得分:2)

不容易。由于您使用的是文字而不是asp.net控件(如下拉列表),因此asp.net不会为您在后面的代码中创建控件。

话虽如此,您应该能够通过Request参数访问该值。

var value = Request["populationSelect"];

更好的解决方案是在页面上创建一个下拉列表控件并将数据绑定到它。

if (!IsPostBack)
{
    List<ListItem> data = new List<ListItem>();
    using (IDataReader reader = SqlHelper.GetDataReader(sql.ToString()))
    {
        //sb.AppendLine("<div class=\"narrowRes\">Poulation</div><select name=\"populationSelect\" class=\"narrowResSelect\"><option value=\"0\">All populations</option>");

        while (reader.Read())
        {
            int pid = reader.IsDBNull(0) ? -1 : reader.GetInt32(0);
            string population = reader.IsDBNull(1) ? string.Empty : reader.GetString(1);

            population = population.Trim();
            data.Add(new ListItem(population, pid.ToString()));
            //sb.AppendLine(string.Format("<option value=\"{0}\">{1}</option>", pid, population));
        }
    }
    DropDownList1.DataSource = data;
    DropDownList1.DataBind();
}