简体   繁体   English

如何使用 DataSet 和 DataAdapter C#/asp.net 进行删除?

[英]How to delete using DataSet and DataAdapter C#/asp.net?

在此处输入图片说明 How can I delete a row from Database using DataSet and DataAdapter (I'm not allowed to SqlCommand)>如何使用 DataSet 和 DataAdapter 从数据库中删除一行(我不允许使用 SqlCommand)>

Table has four columns表有四列

UserId(auto-generated) |用户 ID(自动生成) | UserName |用户名 | Age |年龄 | Salary薪水

I tried the code below but it throws NUll Exception when i click Button3_Click(Delete Button)我尝试了下面的代码,但是当我单击 Button3_Click(Delete Button) 时它会抛出 NULL Exception

System.NullReferenceException: 'Object reference not set to an instance of an object.' System.NullReferenceException: '未将对象引用设置为对象的实例。' System.Data.DataRowCollection.Find(...) returned null. System.Data.DataRowCollection.Find(...) 返回 null。

    string s = 
    ConfigurationManager.ConnectionStrings["student"].ConnectionString;
      protected void Page_Load(object sender, EventArgs e)
        {
           using (SqlConnection con = new SqlConnection(s))
         {
            string query = "select * from student";
            using (SqlDataAdapter da = new SqlDataAdapter(query,con))
            {
                DataSet ds = new DataSet();
                da.Fill(ds);
                ds.Tables[0].PrimaryKey = new DataColumn[] { 
                ds.Tables[0].Columns["UserName"] };
                ViewState["query"] = query;
                ViewState["dataset"] = ds;
            }
        }
    }




 protected void Button3_Click(object sender, EventArgs e)
    {
        using (SqlConnection con = new SqlConnection(s))
        {
            using (SqlDataAdapter da = new 

             SqlDataAdapter((string)ViewState["query"],con))
            {

                DataSet ds = (DataSet)ViewState["dataset"];

                ds.Tables[0].Rows.Find("'" + TextBox2.Text + "'").Delete();
                SqlCommandBuilder com = new SqlCommandBuilder(da);
                da.Update(ds);


            }
        }
    }

I'm pretty sure that UserId is the primary-key of your DataTable.我很确定UserId是您的 DataTable 的主键。 So you can use DataRowCollection.Find (if no key is defined you get a MissingPrimaryKeyException ).所以你可以使用DataRowCollection.Find (如果没有定义键,你会得到一个MissingPrimaryKeyException )。 But of course you need to specify the UserId and not the UserName .但当然您需要指定UserId而不是UserName Otherwise Find returns null which causes your exception.否则Find返回null导致您的异常。 Your screenshot shows that you are passing the UserName您的屏幕截图显示您正在传递UserName

Instead of Find you can use LINQ:您可以使用 LINQ 代替Find

DataRow rowToDelete =  ds.Tables[0].AsEnumerable()
   .FirstOrDefault(r => r.Field<string>("UserName") == TextBox2.Text.Trim());
if(rowToDelete != null) 
{
    rowToDelete.Delete();
    // ...
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM