当我在浏览器上单击“更新”按钮后进行调试时,它会在GridView1_RowUpdating
中的以下行引发NullReferenceException:
dr["Phone Number"] = e.NewValues["Phone Number"];
完整代码:
public partial class DataBound : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e) { }
private void getCacheData()
{
if (Cache["DATASET"] != null)
{
GridView1.DataSource = Cache["DATASET"];
GridView1.DataBind();
}
}
private void getDataDB()
{
String connectionString = ConfigurationManager.ConnectionStrings["MySqlConnectionString"].ConnectionString;
MySqlConnection con = new MySqlConnection(connectionString);
MySqlDataAdapter adp = new MySqlDataAdapter("select `Customer ID`,`Customer Name`,`Phone Number` from customer", con);
DataSet ds = new DataSet();
adp.Fill(ds, "Customer");
ds.Tables["Customer"].PrimaryKey = new DataColumn[] { ds.Tables["Customer"].Columns["Customer ID"] };
Cache.Insert("DATASET", ds, null, DateTime.UtcNow.AddHours(24), System.Web.Caching.Cache.NoSlidingExpiration);
GridView1.DataSource = ds;
GridView1.DataBind();
}
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
getCacheData();
}
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
try
{
DataSet ds = (DataSet)Cache["DATASET"];
DataRow dr = ds.Tables["Customer"].Rows.Find(e.Keys["Customer ID"]);
dr["Phone Number"] = e.NewValues["Phone Number"];
dr["Customer Name"] = e.NewValues["Customer Name"];
Cache.Insert("DATASET", ds, null, DateTime.UtcNow.AddHours(24), System.Web.Caching.Cache.NoSlidingExpiration);
GridView1.EditIndex = -1;
getCacheData();
}
catch (Exception ex)
{
String errorMessage = ex.Message;
}
}
protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
GridView1.EditIndex = -1;
getCacheData();
}
protected void btnGetDataDB_Click(object sender, EventArgs e)
{
getDataDB();
}
}