我的页面加载中的代码背后有代码,用于设置下拉列表文本和值。我选择一个值,它重新加载页面,因为我有自动回发。即使在回发后我也需要保持选择的价值。我该怎么做呢?以下是我的代码:
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++;
}
}
答案 0 :(得分:0)
有一个名为Page.IsPostBack的Page属性,用于指示页面是第一次呈现还是正在加载以响应回发。
因此,您可以将此属性与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++;
}
}
}
答案 1 :(得分:0)
您需要使用IsPostBack()
验证:
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++;
}
}
}
答案 2 :(得分:0)
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;
}
}