[英]Deleting a row from a gridview in asp.NET
I wants to delete a row from a gridview .Here is my code 我想从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();
}
The code is working fine but when i try to click on the delete link. 该代码工作正常,但是当我尝试单击删除链接时。 I get a runtime error in this line "ds.Tables["Bus_Table"].Rows[e.RowIndex].Delete();" 我在此行“ 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
I can't figure out the problem. 我不知道问题所在。 Please help 请帮忙
Either : 要么:
Session["ds1"]
doesn't exist (because your DataSet isn't in Session), Session["ds1"]
不存在(因为您的数据集不在会话中), Because the code's all chained together, you have two options to find out which: 因为代码都链接在一起,所以您有两个选择来找出哪个:
ds
, ds.Tables["Bus_Table"]
and ds.Tables["Bus_Table"].Rows[e.RowIndex]
, OR 连接调试器并检查ds
, ds.Tables["Bus_Table"]
和ds.Tables["Bus_Table"].Rows[e.RowIndex]
或 You appear to be binding to the employee
table: 您似乎绑定到employee
表:
gvdetails.datasource=ds.Tables["employee"];
and deleting from the Bus_Table
table: 并从Bus_Table
表中删除:
ds.Tables["Bus_Table"].Rows[e.RowIndex].Delete();
That's not going to work, is it? 那是行不通的,对吗?
// THIS IS A EXAMPLE AND THOUGHT IT MIGHT HELP //这是一个示例,可能会有所帮助
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();
}
}
} }
Hope i am clear now... 希望我现在明白了...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.