我目前正在使用ASP.Net Webforms开发一个系统,我在我的一个页面上有这个代码:
namespace mypms.View
{
public partial class Reports : System.Web.UI.Page
{
private string truck_id = null;
MySqlConnection conn = new MySqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
protected void Page_Load(object sender, EventArgs e)
{
truck_id = this.Request.QueryString["u"] != null ? this.Request.QueryString["u"] : Session["truck_id"] != null ? Session["truck_id"].ToString() : "";
connectDB();
}
private void connectDB()
{
try
{
conn.Open();
string selectUserQuery = @"SELECT * FROM thesis.joborder as jo inner join thesis.jobordermaterials as jom ON jom.jobID = jo.jobId Where jom.truck_id = '" + truck_id + "'";
MySqlCommand cmd = new MySqlCommand(selectUserQuery, conn);
foreach (DbDataRecord rowData in cmd.ExecuteReader())
{
populateNewTableRow(rowData);
}
}
catch (MySqlException ex)
{
System.Diagnostics.Debug.WriteLine("ERROR: " + ex.ToString());
}
finally
{
conn.Close();
}
}
private void populateNewTableRow(DbDataRecord rowData)
{
TableRow tr = new TableRow();
TableCell cell2 = new TableCell();
cell2.Text = rowData.GetInt32(rowData.GetOrdinal("jobId")).ToString();
tr.Cells.Add(cell2);
TableCell cell3 = new TableCell();
cell3.Text = rowData.GetString(rowData.GetOrdinal("odometerReading")).ToString();
tr.Cells.Add(cell3);
TableCell cell4 = new TableCell();
cell4.Text = rowData.GetString(rowData.GetOrdinal("description")).ToString();
tr.Cells.Add(cell4);
TableCell cell5 = new TableCell();
cell5.Text = rowData.GetInt32(rowData.GetOrdinal("quantity")).ToString();
tr.Cells.Add(cell5);
TableCell cell6 = new TableCell();
cell6.Text = rowData.GetString(rowData.GetOrdinal("remarks")).ToString();
tr.Cells.Add(cell6);
TableCell cell7 = new TableCell();
cell7.Text = rowData.GetString(rowData.GetOrdinal("mechanic")).ToString();
tr.Cells.Add(cell7);
tbl_MaitenanceRecord.Rows.Add(tr);// THIS (Null Reference Exception)
}
}
我在此行收到错误System.NullReferenceException: Object reference not set to an instance of an object.
tbl_MaitenanceRecord.Rows.Add(tr);
我很确定我的代码是正确的。这个空引用异常的原因是什么?提前致谢
答案 0 :(得分:2)
我认为更好的想法是在你的桌子上使用databind方法。检查调试器每个rowData是什么。如果上部调用中的某个对象为null,则可能会出现问题。检查你的调用堆栈并检查绑定到你的表的每个对象,因为我说它可能是一个问题。 我可能也是表inicialization的问题。您可以将您的Web代码放入问题和设计师,尤其是表格部分。