I add values in a dropdownlist in a method as given below
pageload()
{
method(type);
}
public void method(type)
{
dropdownlist1.items.clear();
if(type == "Student")
{
dropdownlist1.items.add("abc");
dropdownlist1.items.add("xyz");
}
}
when i select dropdownlist value, it will lost after postback and i do this for retrieveing
public void method(type)
{
string selection = dropdownlist1.selectedItem.text;
Viewstate["selectionValue"] = selection;
dropdownlist1.items.clear();
if(type == "Student")
{
dropdownlist1.items.add("abc");
dropdownlist1.items.add("xyz");
}
}
but an exception occur at this line:
string selection = dropdownlist1.selectedItem.text;
The exception message:
{object reference is not set to an instance of an object}
And i know why it comes. because when first time dropdownlist1
load it could not find the object of dropdownlist
, so that's exception occur. my quection is where i retrieve dropdownlist1
selection value that would not lost even after postback
.
This question is really about the asp.net page lifecycle. Here's a reference: http://msdn.microsoft.com/en-us/library/ms178472.ASPX
I'm guessing that you're creating your dropdown on page load, but when postback occurs you're trying to read from your dropdown before the page controls have been initialized.
You should check for IsPostBack in your onload function, and if it's true, then try and rebuild your dropdown there.
I think it could be happening because the dropdown might not be having any items when the line
string selection = dropdownlist1.selectedItem.text;
is executed.
you would have to make sure data is bound to the dropdown before that line gets executed or add a condition like this.
string selection="";
if(dropdownlist1.items.count>0)
selection = dropdownlist1.selectedItem.text;
Most probably you dont have even a single item in drop-down and you are trying to invoke selecteditem.text. so showing the error message. Put a break point to find out why you dont have items in dropdownlist1.
You should clarify first which is the null
. Is it the dropdownlist1.selectedItem
or the dropdownlist1
? I would suggest using the Viewstate["selectionValue"] = selection;
statement on the selectedIndeChanged
event of the dropdownlist. Then I would use the viewstate content in the onLoad
event handler to populate the dropdownlist selection.
Anyway, I suppose Michael J. Anderson is right. You should invest some time on understanding the asp.net life cycle. Misusing the event mechanism of ASP.NET is very often based on poor understanding of ASP.NET lifecycle.
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.