【问题标题】:Error : Update requires a valid UpdateCommand when passed DataRow collection with modified rows错误:当传递带有修改行的 DataRow 集合时,更新需要有效的 UpdateCommand
【发布时间】:2013-09-05 20:23:21
【问题描述】:

我正在使用 Paging 来显示 datagridview 中的数据,但是当我尝试使用 updatebutton 更新任何数据时,应在 datagridview 以及数据库中更新数据。

但我收到此错误:

在传递 DataRow 集合时,更新需要有效的 UpdateCommand 修改后的行

发生在这一行:

adp1.Update(dt);//here I am getting error

下面是代码

public partial class EditMediClgList : Form
    {        
        public EditMediClgList()
        {
            InitializeComponent();
            try
            {
                con = new OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=db1.mdb");
                con.Open();
            }
            catch (Exception err)
            {
                MessageBox.Show("Error:" +err);
            }

            cmd1 = new OleDbCommand("Select * from MedicalColeges order by MedicalClgID", con);
            ds = new DataSet();
            adp1 = new OleDbDataAdapter(cmd1);
            adp1.Fill(ds, "MedicalColeges");
            dataGridView1.DataSource = ds;

            // Get total count of the pages; 
            this.CalculateTotalPages();
            // Load the first page of data; 
            this.dataGridView1.DataSource = GetCurrentRecords(1, con);

        }
        private void CalculateTotalPages()
        {
            int rowCount = ds.Tables["MedicalColeges"].Rows.Count;
            this.TotalPage = rowCount / PageSize;
            if (rowCount % PageSize > 0) // if remainder is more than  zero 
            {
                this.TotalPage += 1;
            }
        }
        private DataTable GetCurrentRecords(int page, OleDbConnection con)
        {
             dt = new DataTable();

            if (page == 1)
            {
                cmd2 = new OleDbCommand("Select TOP " + PageSize + " * from MedicalColeges ORDER BY MedicalClgID", con);
                // CurrentPageIndex++;
            }
            else
            {
                int PreviouspageLimit = (page - 1) * PageSize;

                cmd2 = new OleDbCommand("Select TOP " + PageSize +
                    " * from MedicalColeges " +
                    "WHERE MedicalClgID NOT IN " +
                "(Select TOP " + PreviouspageLimit + " MedicalClgID from MedicalColeges ORDER BY MedicalClgID) ", con); // +
                //"order by customerid", con);
            }
            try
            {
                // con.Open();
                this.adp1.SelectCommand = cmd2;
                this.adp1.Fill(dt);
                txtPaging.Text = string.Format("page{0} of {1} pages", this.CurrentPageIndex, this.TotalPage);
            }
            finally
            {
               // con.Close();
            }
            return dt;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            try
            {                
                adp1.Update(dt);//here I am getting error
            }
            catch (Exception err)
            {
                MessageBox.Show(err.Message.ToString());
            }

        }
}

【问题讨论】:

    标签: c# .net ado.net dataadapter


    【解决方案1】:

    您仅使用Select 命令创建了OleDbDataAdapter

    adp1 = new OleDbDataAdapter(cmd1);
    

    OleDbDataAdapter 需要使用有效的UpdateInsert, Delete 命令来保存数据,如下所示:

    adp1.Update(dt);//here I am getting error
    

    您只需要使用OleDbCommandBuilder 即可为您生成命令:

    adp1 = new OleDbDataAdapter();
    adp1.SelectCommand = cmd1; // cmd1 is your SELECT command
    OleDbCommandBuilder cb = new OleDbCommandBuilder(adp1);
    

    编辑

    由于您在运行时更改OleDbDataAdapter的Select命令进行分页,因此您需要在每次保存数据时进行初始化:

    private void button1_Click(object sender, EventArgs e)
        {
            try
            {                
                adp1.SelectCommand = cmd1; // cmd1 is your SELECT command
                OleDbCommandBuilder cb = new OleDbCommandBuilder(adp1);
                adp1.Update(dt); //here I hope you won't get error :-)
            }
            catch (Exception err)
            {
                MessageBox.Show(err.Message.ToString());
            }
    
        }
    

    【讨论】:

    • 是的,你是对的,现在我没有收到错误并且数据已更新,谢谢:)
    【解决方案2】:

    可能是您在表中缺少主键。您需要确保在数据库表中的列上设置了主键。

    【讨论】:

      【解决方案3】:

      我不得不将我的(递增)索引列更改为primary key of my table(正如 Eaint 建议的那样)。在此之后,我必须在设计器视图中拉出 DataSet.xsd,右键单击可视 DataTable 对象并选择配置。当 TableAdapter 配置向导打开时,我单击了高级选项按钮。我检查了生成插入、更新和删除语句复选框,然后确定并完成。在此之后(仍在设计器视图中),我选择了可​​视化 TableAdapter 对象,它为我提供了所有完整属性。 SQL 是自动生成的。我花了一段时间才找到它,所以我希望它对某人有所帮助。

      【讨论】:

        【解决方案4】:

        感谢“@Chris”,上面的代码对我有用。 我需要指定更新时将更新的数据库表名称。 您可以在此处阅读更多相关信息:

        DataAdapter: Update unable to find TableMapping['Table'] or DataTable 'Table'

        // This Adapter and Dataset are used for Populating my datagridview, 
        // so I use them also when I need to Update the Datagridview
        
        SqlDataAdapter kundeTlfAdapter;
        DataSet kundeTlfDataSet; 
        
        try
        {
            SqlConnection connection = new SqlConnection("Data source=BG-1-PC\\SQLEXPRESS; Database = Advokathuset; User Id = abc; Password = abc;");
            SqlCommand cmd1 = new SqlCommand("Select* From Kunde_Tlf", connection);
            SqlCommandBuilder builder = new SqlCommandBuilder(kundeTlfAdapter);
            kundeTlfAdapter.SelectCommand = cmd1; // cmd1 is your SELECT command
        
            kundeTlfAdapter.Update(kundeTlfDataSet, "Kunde_Tlf"); //I get eror here if I dont add the name of the table that needs Update "Kunde_Tlf"
        }
        catch (Exception err)
        {
            MessageBox.Show(err.Message.ToString());
        }
        

        【讨论】:

          猜你喜欢
          • 2010-10-09
          • 1970-01-01
          • 2010-12-23
          • 2014-07-10
          • 2016-04-18
          • 2011-05-05
          • 2016-01-13
          • 2016-10-11
          相关资源
          最近更新 更多