I created a server control and test.aspx Code is shown below .
When dll is loaded , RenderContents()
function gets called.
Control transfer to DataSource property ,
but ViewState["DataSource"]
returns null
.
To avoid it , I initialized ViewState["DataSource"]
using -
ViewState["DataSource"] = _Pages_dummy;
My Question is -
if i do not want to use initialization , is there any alternate way so that ViewState["DataSource"]
will not return null
value "?
=================================== ===============================================
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace ServerControl2
{
[DefaultProperty("Text")]
[ToolboxData("<{0}:ServerControl1 runat=server></{0}:ServerControl1>")]
public class ServerControl1 : WebControl
{
private string[,] _Pages_dummy= { {"1","2","3","4"} , {"11","22","33","44"}};
public ServerControl1()
{
ViewState["DataSource"] = _Pages_dummy;
// if user do not initialize viewstate , we use dummmey array .
}
public ServerControl1(string[,] pages)
{
ViewState["DataSource"] = pages;
// user must initialize viewstate .
}
[Bindable(true)]
[Category("Appearance")]
[DefaultValue("")]
[Localizable(true)]
public string[,] DataSource
{
get
{
return (string[,])ViewState["DataSource"];
}
set
{
ViewState["DataSource"] = value;
}
}
[Bindable(true)]
[Category("Appearance")]
[DefaultValue("")]
[Localizable(true)]
protected override HtmlTextWriterTag TagKey
{
get
{
return HtmlTextWriterTag.Div;
}
}
protected override void RenderContents(HtmlTextWriter output)
{
output.WriteBeginTag("div");
if (DataSource != null)
{
for (int i = 0; i < DataSource.GetLength(0); i++)
{
for (int j = 0; j < DataSource.GetLength(1); j++)
{
}
}
}
} // RenderContents
}// class
}// namespace
test.aspx.cs
ServerControl2.ServerControl1 n1 = new ServerControl2.ServerControl1();
n1.DataSource[0,0] = "hjkhjk";
n1.DataSource[0,1] = "jkljk";
n1.DataSource[0,2] = "hjk";
n1.DataSource[0,3] = "fjgfjhhgj";
Response.Write(n1.DataSource[0,0]);
Response.Write(n1.DataSource[0,1]);
Response.Write(n1.DataSource[0,2]);
Response.Write(n1.DataSource[0,3]);
Check if the viewstate is null in the Datasource property. As long as you use the property instead of Viewstate("Datasource") directly, you should be fine.
[Bindable(true)]
[Category("Appearance")]
[DefaultValue("")]
[Localizable(true)]
public string[,] DataSource
{
get
{
string[,] value = (string[,])ViewState["DataSource"];
if (value == null) {
return __Pages_dummy
}
return value ;
}
set
{
ViewState["DataSource"] = value;
}
}