我创建了一个服务器控件, test.aspx 代码如下所示。
加载dll时,会调用RenderContents()
函数
控制传输到DataSource属性,
但是ViewState["DataSource"]
会返回null
。
为避免这种情况,我使用 -
初始化ViewState["DataSource"]
ViewState["DataSource"] = _Pages_dummy;
我的问题是 -
如果我不想使用初始化,是否有任何替代方式,以便ViewState["DataSource"]
不会返回null
值“?
=================================== ============ ===================================
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]);
答案 0 :(得分:0)
检查Datasource属性中的viewstate是否为null。只要您直接使用该属性而不是Viewstate(“Datasource”),您应该没问题。
[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;
}
}