我想从gridview中删除一行。这是我的代码
//page load event
if(page.isPostback==false)
{
dataset ds=null;
ds=(dataset)Session["ds1"];
//session will contain dataset ds1 with data selected by user
if(ds!=null)
{
gvdetails.datasource=ds.Tables["Bus_Table"];
gvdetails.DataBind();
}
}
protected void gvdetails_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
DataSet ds = (DataSet)Session["ds1"];
ds.Tables["Bus_Table"].Rows[e.RowIndex].Delete();
ds.Tables["Bus_Table"].AcceptChanges();
Session["ds1"] = ds;
gvDetails.DataSource = ds.Tables["Bus_Table"];
gvDetails.DataBind();
}
代码工作正常,但是当我尝试点击删除链接时。我在这行“ds.Tables [”Bus_Table“]中得到一个运行时错误。行[e.RowIndex] .Delete();”
error :Object reference not set to an instance of an object.NULLREFERENCEEXCEPTION was unhandled by the usercode.Use the "new " keyword to create an object instance
我无法弄清楚问题。请帮忙
答案 0 :(得分:1)
要么:
Session["ds1"]
不存在(因为您的DataSet不在Session中),因为代码全部链接在一起,所以有两个选项可以找出:
ds
,ds.Tables["Bus_Table"]
和ds.Tables["Bus_Table"].Rows[e.RowIndex]
,或 答案 1 :(得分:0)
您似乎绑定到employee
表:
gvdetails.datasource=ds.Tables["employee"];
并从Bus_Table
表中删除:
ds.Tables["Bus_Table"].Rows[e.RowIndex].Delete();
那不行,是吗?
答案 2 :(得分:-2)
//这是一个例子并且有可能帮助
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
string EmployeeID = GridView1.DataKeys[e.RowIndex].Value.ToString();
string Query = “delete Employee where Employee.EmployeeID = “ + EmployeeID;
BindGridData(Query);
}
private void BindGridData(string Query)
{
string connectionstring = ConfigurationManager.ConnectionStrings["SampleConnectionString"].ConnectionString;
using (SqlConnection conn = new SqlConnection(connectionstring))
{
conn.Open();
using (SqlCommand comm = new SqlCommand(Query, conn))
{
SqlDataAdapter da = new SqlDataAdapter(comm);
DataSet ds = new DataSet();
da.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
}
}
}
希望我现在很清楚......