Getting/Setting Select Box in Literal from ASP.Net Code-Behind
I have the below code that gets added to a literal in my form. How in the code behind to I grab get/set the data from the 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();
}
Not easily. Since you're using a literal instead of an asp.net control (like a drop down list), asp.net does not create a control for you to use in the code behind.
That being said you should be able to access the value through the Request parameters.
var value = Request["populationSelect"];
A better solution would be to create a dropdownlist control on the page and databind to it.
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();
}
精彩评论