Below code works the first time - at Page_Load it's working, data showing in the gridview control. But when I add new data to the database and retrieve I get an error.
I put the breakpoint and I checked step-by-step: DataTable dtsent is not null, it has data, but when it comes to gridSent.DataSource=dtsent an error occurs:
NullReferenceException was unhandled by user code
Object reference not set to an instance of an object
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;
}
}