下面的代码第一次工作 - 在Page_Load
工作时,数据显示在gridview控件中。但是,当我向数据库添加新数据并检索时,我收到错误。
我设置断点并逐步检查:DataTable
dtsent
不是null
,它有数据,但是当涉及到gridSent.DataSource=dtsent
时出错发生:
NullReferenceException未被用户代码
处理 对象引用未设置为对象的实例
public void BindGridSent()
{
try
{
BusinessObject.BusinessObject bogetMS = new BusinessObject.BusinessObject();
bogetMS.UserID = Convert.ToInt32(HttpContext.Current.Session["uid"]);
DataTable dtsent = new DataTable();
dtsent.Columns.Add("msgID");
dtsent.Columns.Add("ToUsername");
dtsent.Columns.Add("msgContent");
dtsent.Columns.Add("msg_sent_date");
dtsent.Columns.Add("fullmsgContent");
DataRow dwsent = null;
DataSet dssent = businssLogicMS.MessageSentList_BAL(bogetMS);
if (dssent.Tables[0].Rows.Count > 0)
{
for (int i = 0; i < dssent.Tables[0].Rows.Count; i++)
{
dwsent = dtsent.NewRow();
string msgID = dssent.Tables[0].Rows[i]["msgID"].ToString();
dwsent["msgID"] = msgID;
//string username=" <b>" + dssent.Tables[0].Rows[i]["ToUsername"].ToString() + "</b> ";
string username = dssent.Tables[0].Rows[i]["ToUsername"].ToString();
dwsent["ToUsername"] = username;
string stmsg = dssent.Tables[0].Rows[i]["msgContent"].ToString();
string message = stmsg.Substring(0, Math.Min(stmsg.Length, 80)) + "...";
string editmsgbody = message.ToString().Replace("<br />", Environment.NewLine);
dwsent["msgContent"] = editmsgbody;
dwsent["fullmsgContent"] = stmsg;
string date = String.Format("{0:MMM dd}", dssent.Tables[0].Rows[i]["msg_sent_date"]);
dwsent["msg_sent_date"] = "<font color='Red'>" + date + "</font>";
dtsent.Rows.Add(dwsent);
}
gridSent.DataSource = dtsent; --- Error Occurs Here
gridSent.DataBind();
}
else
{
dtsent.Rows.Add(dtsent.NewRow());
gridSent.DataSource = dtsent;
gridSent.DataBind();
int columncount = gridSent.Rows[0].Cells.Count;
gridSent.Rows[0].Cells.Clear();
gridSent.Rows[0].Cells.Add(new TableCell());
gridSent.Rows[0].Cells[0].ColumnSpan = columncount;
gridSent.Rows[0].Cells[0].Text = "No Record Found....";
}
}
catch (Exception ex)
{
throw ex;
}
}