【问题标题】:Getting/Setting Select Box in Literal from ASP.Net Code-Behind从 ASP.Net Code-Behind 获取/设置文本中的选择框
【发布时间】:2011-10-27 14:27:46
【问题描述】:

我将以下代码添加到表单中的文字中。我如何在后面的代码中获取/设置来自 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();
}

【问题讨论】:

  • 您确定需要动态创建这些控件吗?是否有任何理由不能使用创建 asp.net DropDownList 并从代码后面添加该控件?
  • 我想我应该切换到那个,有没有办法抓住选择名称=“人口”?

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


【解决方案1】:

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

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

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

【讨论】:

  • 我会将其从文字控件中切换出来以使其更容易
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-04-12
  • 1970-01-01
  • 2015-12-06
相关资源
最近更新 更多