我有一个拥有大约1000个用户的数据库,每个用户都有一个或多个与之相关的日记条目。在页面的左侧,我有一个搜索框,工作人员可以在数据库中搜索用户并选择用户。从左侧搜索中选择用户后,工作人员可以编写日记帐分录,并将该条目添加到数据库中,并将通过用户ID放入与所选用户相关的表中。目前,如果工作人员在没有选择用户的情况下尝试提交日记帐分录,我会收到一条错误消息,我想实现某种自定义错误消息,就像一个简单的消息框所示,"请搜索并选择用户& #34;
我认为下面的代码可以正常工作,但它仍然会重定向到ASP.NET错误页面。关于什么事情的任何想法?
protected void btnSubmitJournalEntry_Click(object sender, EventArgs e)
{
if (SearchGrid.SelectedRow.Cells[3].Text != "")
{
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alertMessage", "alert('Please search and select user')", true);
}
else
{
//Start database connection
string constr = @"Provider=Microsoft.Jet.OLEDB.4.0; Data Source=D:\Sites\App_Data\access.mdb";
string cmdstr = "insert into JournalEntries(StudentID, Topic, SubTopic, JournalDate, Advisor, FaceTime, Notes, Followup, Author) values(@StudentID, @Topic, @SubTopic, @JournalDate, @Advisor, @FaceTime, @Notes, @Followup, @Author)";
OleDbConnection con = new OleDbConnection(constr);
OleDbCommand com = new OleDbCommand(cmdstr, con);
con.Open();
//The following fields are added from the journal entry form to the corresponding database fields
com.Parameters.AddWithValue("@StudentID", SearchGrid.SelectedRow.Cells[3].Text);
com.Parameters.AddWithValue("@Topic", ddlTopic.Text);
com.Parameters.AddWithValue("@SubTopic", txtSubTopic.Text);
com.Parameters.AddWithValue("@JournalDate", txtDate.Text);
com.Parameters.AddWithValue("@Advisor", txtAdvisor.Text);
com.Parameters.AddWithValue("@FaceTime", txtFacetime.Text);
com.Parameters.AddWithValue("@Notes", txtNotes.Text);
com.Parameters.AddWithValue("@Followup", txtFollowup.Text);
com.Parameters.AddWithValue("@Author", ddlAuthor.Text);
com.ExecuteNonQuery();
con.Close();
//End
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alertMessage", "alert('Journal entry has been successfully added!')", true);
}
}
这是我不断收到的错误消息。
Object reference not set to an instance of an object.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.
Source Error:
Line 27: protected void btnSubmitJournalEntry_Click(object sender, EventArgs e)
Line 28: {
Line 29: if (SearchGrid.SelectedRow.Cells[3].Text != "")
Line 30: {
Line 31:
答案 0 :(得分:1)
您收到此错误是因为SearchGrid.SelectedRow
为NULL。所以当SearchGrid.SelectedRow
为NULL时,那么单元格也是NULL,但是你正在检查Cells [3]是否存在?
您需要做的只是检查SearchGrid.SelectedRow是否为NULL,因为您不关心选择哪一行,您可以执行以下操作:
protected void btnSubmitJournalEntry_Click(object sender, EventArgs e)
{
if (SearchGrid.SelectedRow == null)
{
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alertMessage", "alert('Please search and select user')", true);
}
else
{
....
}
}