C# 获取值以在回发下拉列表后保持选中状态
我的页面加载中有代码隐藏代码,它设置了一个下拉列表,列出文本和值。每当我选择一个值时,它都会重新加载页面,因为我已经打开了“自动发帖”。我需要该值即使在回发后仍保持选中状态。我该怎么做呢?下面是我的代码:C# 获取值以在回发下拉列表后保持选中状态,c#,asp.net,drop-down-menu,code-behind,C#,Asp.net,Drop Down Menu,Code Behind,我的页面加载中有代码隐藏代码,它设置了一个下拉列表,列出文本和值。每当我选择一个值时,它都会重新加载页面,因为我已经打开了“自动发帖”。我需要该值即使在回发后仍保持选中状态。我该怎么做呢?下面是我的代码: protected void Page_Load(object sender, EventArgs e) { List<string> list = new List<string> { "Month", "1", "2", "3", "4", "5
protected void Page_Load(object sender, EventArgs e)
{
List<string> list = new List<string>
{ "Month", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12"};
DropDownListMonth.DataSource = list;
DropDownListMonth.DataBind();
DropDownListMonth.SelectedIndex = 0;
foreach (ListItem item in DropDownListMonth.Items)
{
int i = 0;
string month = Convert.ToString(i);
item.Value = month;
i = Convert.ToInt32(month);
i++;
}
}
有一个名为的页面属性,它指示页面是第一次呈现还是响应回发而加载 因此,您可以将此属性与if条件块一起使用,以避免ddl的重新绑定
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
List<string> list = new List<string>
{ "Month", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12"};
DropDownListMonth.DataSource = list;
DropDownListMonth.DataBind();
DropDownListMonth.SelectedIndex = 0;
foreach (ListItem item in DropDownListMonth.Items)
{
int i = 0;
string month = Convert.ToString(i);
item.Value = month;
i = Convert.ToInt32(month);
i++;
}
}
}
您需要使用验证:
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack())
{
List<string> list = new List<string>
{ "Month", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12"};
DropDownListMonth.DataSource = list;
DropDownListMonth.DataBind();
DropDownListMonth.SelectedIndex = 0;
foreach (ListItem item in DropDownListMonth.Items)
{
int i = 0;
string month = Convert.ToString(i);
item.Value = month;
i = Convert.ToInt32(month);
i++;
}
}
}
多亏了你和我读的另一页。谢谢你想知道为什么是负数:如果任何答案解决了你的问题,你应该点击旁边的复选标记接受它。
DropDownListMonth.DataSource = list;
DropDownListMonth.DataBind();
DropDownListMonth.SelectedIndex = 0;
string selectedValue=DropDownListMonth.SelectedItem.Tostring();
foreach (ListItem item in DropDownListMonth.Items)
{
int i = 0;
string month = Convert.ToString(i);
item.Value = month;
i = Convert.ToInt32(month);
i++;
if(item.Value.Tostring()==selectedValue)
{
item.Selected=true;
}
}