I have a drop down & a label, drop down is binded with a dictionary. When user changes the selected value of drop down I want to update the label. Following code works well but i want to set the initial value of label, I set the value of selected index in page_load, however event does not trigger. How to fix it? is there any page event which can help me solve the issue. I know i can fix it using javascript but I do not want to use JS.
public partial class WebForm1 : System.Web.UI.Page
{
Dictionary<string, string> myDictionary = new Dictionary<string, string>();
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
myDictionary.Add("1", "Test Address 1");
myDictionary.Add("2", "Test Address 2");
myDictionary.Add("3", "Test Address 3");
myDictionary.Add("4", "Test Address 4");
myDictionary.Add("5", "Test Address 5");
drpTest.DataSource = myDictionary;
drpTest.DataTextField = "Key";
drpTest.DataValueField = "Value";
drpTest.DataBind();
// I want to set the index & update the label lblAddress
drpTest.SelectedIndex = 2;
}
}
protected void drpTest_SelectedIndexChanged(object sender, EventArgs e)
{
lblAddress.Text = drpTest.SelectedItem.Value;
}
change label text on pageload. See below.
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
myDictionary.Add("1", "Test Address 1");
myDictionary.Add("2", "Test Address 2");
myDictionary.Add("3", "Test Address 3");
myDictionary.Add("4", "Test Address 4");
myDictionary.Add("5", "Test Address 5");
drpTest.DataSource = myDictionary;
drpTest.DataTextField = "Key";
drpTest.DataValueField = "Value";
drpTest.DataBind();
drpTest.SelectedIndex = 2;
lblAddress.Text = drpTest.SelectedItem.Value; **// add this**
}
}
Hope it works for you.
you should call this function at page load
drpTest_SelectedIndexChanged(null, null)
and it doesn't trigger as normal because you didn't change the dropdown selected value after initializing the page and ready to be used for client
当您定义下拉列表时,请包括drpTest.AutoPostBack = true这将在更改后触发SelectedIndexChanged事件。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.