我正在尝试将页面加载时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;
}
}
答案 0 :(得分:0)
假设我们有以下示例:
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事件将触发 BEFORE Button1_Click事件,因此,viewstate仍然为空。这可以通过将代码传递到 Page_PreRender 事件来管理,该事件将在button_click事件之后触发。
protected void Page_PreRender(object sender, EventArgs e)
{
if (ViewState["messages"] != null)
{
input = (List<string>)ViewState["messages"];
}
}