[英]Deleting a row from a gridview in asp.NET
我想从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”]。Rows [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
我不知道问题所在。 请帮忙
要么:
Session["ds1"]
不存在(因为您的数据集不在会话中), 因为代码都链接在一起,所以您有两个选择来找出哪个:
ds
, ds.Tables["Bus_Table"]
和ds.Tables["Bus_Table"].Rows[e.RowIndex]
或 您似乎绑定到employee
表:
gvdetails.datasource=ds.Tables["employee"];
并从Bus_Table
表中删除:
ds.Tables["Bus_Table"].Rows[e.RowIndex].Delete();
那是行不通的,对吗?
//这是一个示例,可能会有所帮助
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();
}
}
}
希望我现在明白了...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.