带有字符串列表的ViewState
本文关键字:ViewState 列表 字符串 | 更新日期: 2023-09-27 18:14:59
我试图保存信息从Gridview页面加载到字符串列表。然后我想把这些信息用电子邮件发送出去。我在网上找过这方面的信息,到目前为止我什么也没找到。我不明白我的ViewState实现是否在错误的地方是错误的或简单的。请帮忙吗?
protected void Page_Load(object sender, EventArgs e)
{
if (ViewState["messages"] != null)
{
messages = (List<string>)ViewState["messages"];
}
if (Page.IsPostBack)
{
changeByVendor();
//mailFunction(messages);
}
if (!IsPostBack)
{
mailFunction(messages);
}
}
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
if ((GridView1.DataSourceID == "SqlDataSource2" || GridView1.DataSourceID == "SqlDataSource1") && !(e.Row.Cells[11].Text.Equals(" ")))
{
DateTime myDate = Convert.ToDateTime(e.Row.Cells[11].Text);
if (DateTime.Now > myDate)
{
e.Row.ForeColor = System.Drawing.Color.Red;
}
DateTime myDate2 = Convert.ToDateTime(e.Row.Cells[13].Text);
if (myDate2 > DateTime.Now && myDate2 < DateTime.Now.AddDays(28))
{
e.Row.Cells[13].BackColor = System.Drawing.Color.Yellow;
string thisRow = "";
for (int i = 0; i < e.Row.Cells.Count; i++)
{
thisRow = thisRow + e.Row.Cells[i];
}
messages.Add(thisRow);
}
}
else if (GridView1.DataSourceID == "SqlDataSource4" && !(e.Row.Cells[6].Text.Equals(" ")))
{
DateTime myDate = Convert.ToDateTime(e.Row.Cells[6].Text);
if (DateTime.Now > myDate)
{
e.Row.ForeColor = System.Drawing.Color.Red;
}
DateTime myDate2 = Convert.ToDateTime(e.Row.Cells[7].Text);
if (myDate2 > DateTime.Now && myDate2 < DateTime.Now.AddDays(28))
{
e.Row.Cells[7].BackColor = System.Drawing.Color.Yellow;
}
}
ViewState["messages"] = messages;
}
}
假设我们有以下示例:
List<string> input = new List<string>();
protected void Page_Load(object sender, EventArgs e)
{
if (ViewState["messages"] != null)
{
input = (List<string>)ViewState["messages"];
}
}
protected void Button1_Click(object sender, EventArgs e)
{
List<string> msgs = new List<string>() { "1", "2", "3" };
ViewState["messages"] = msgs;
}
这当然会在视图状态中存储字符串列表。问题是,当我们触发按钮单击事件时,Page_Load事件将在 Button1_Click事件之前触发,因此,视图状态仍然是空的。这可以通过将代码传入Page_PreRender事件来管理,该事件将在button_click事件之后触发。
protected void Page_PreRender(object sender, EventArgs e)
{
if (ViewState["messages"] != null)
{
input = (List<string>)ViewState["messages"];
}
}