I have a .Net 3.5 web application that has view state disabled on the page level but enabled on the dropdown control. During post back of the dropdown I am getting the following exception
Object reference not set to an instance of an object.
This exception happens on following line:
string selectedVal = ddlStatus.SelectedItem.Value;
The Control.ViewStateMode Property is from .Net 4.0 onwards. It meets the purpose if I were using 4.0
To disable view state for a page and to enable it for a specific control on the page, set the EnableViewState property of the page and the control to true, set the ViewStateMode property of the page to Disabled, and set the ViewStateMode property of the control to Enabled.
How can we resolve the problem when I am using .Net 3.5 framework?
CODE
public partial class FormattingTest : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
Status status1 = new Status() { StatusCode = 1, StatusDescription = "Inctive" };
Status status2 = new Status() { StatusCode = 2, StatusDescription = "Active" };
List<Status> statucCollection = new List<Status>();
statucCollection.Add(status1);
statucCollection.Add(status2);
ddlStatus.DataTextField = "StatusDescription";
ddlStatus.DataValueField = "StatusCode";
ddlStatus.DataSource = statucCollection;
ddlStatus.DataBind();
//Assembly Version - 3.5.0.0
string version = System.Reflection.Assembly
.GetExecutingAssembly()
.GetReferencedAssemblies()
.Where(x => x.Name == "System.Core").First().Version.ToString();
Response.Write(version);
}
string selectedVal = ddlStatus.SelectedItem.Value;
int y = 0;
}
}
public class Status
{
public int StatusCode { get; set; }
public string StatusDescription { get; set; }
}
MARKUP
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="FormattingTest.aspx.cs" Inherits="FormattingTest"
EnableViewState="false" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<asp:DropDownList ID="ddlStatus" runat="server" AutoPostBack="true" EnableViewState="true" >
</asp:DropDownList>
</form>
</body>
</html>
Reference: