當傳遞擁有已刪除資料列的 DataRow 集合時,更新需要有效的 DeleteCommand。

解决方案 »

  1.   

    倒,你的CommandName是不是叫Delete?
      

  2.   

    我沒寫DEL方法啊,微軟沒有幫我們實現嗎?
      

  3.   

    没太明白,楼主是怎么删除的数据的??楼主是不是这个意思?删除DataGridView中的记录时,同时更新到数据库中?
      

  4.   

    我想你可能是没有用SqlCommandBuilder...如果你不想写sql语句,让其自动生成,可以用SqlCommandBuilder...SqlDataAdapter+SqlCommandBuilder...adapter.Update(DataTable)即可..
      

  5.   

    namespace WindowsApplication2 {
        using System;
        
        
        [System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "2.0.0.0")]
        [Serializable()]
        [System.ComponentModel.DesignerCategoryAttribute("code")]
        [System.ComponentModel.ToolboxItem(true)]
        [System.Xml.Serialization.XmlSchemaProviderAttribute("GetTypedDataSetSchema")]
        [System.Xml.Serialization.XmlRootAttribute("TestDataSet")]
        [System.ComponentModel.Design.HelpKeywordAttribute("vs.data.DataSet")]
        public partial class TestDataSet : System.Data.DataSet {
            
            private memberDataTable tablemember;
            
            private System.Data.SchemaSerializationMode _schemaSerializationMode = System.Data.SchemaSerializationMode.IncludeSchema;
            
            [System.Diagnostics.DebuggerNonUserCodeAttribute()]
            public TestDataSet() {
                this.BeginInit();
                this.InitClass();
                System.ComponentModel.CollectionChangeEventHandler schemaChangedHandler = new System.ComponentModel.CollectionChangeEventHandler(this.SchemaChanged);
                base.Tables.CollectionChanged += schemaChangedHandler;
                base.Relations.CollectionChanged += schemaChangedHandler;
                this.EndInit();
            }
            
            [System.Diagnostics.DebuggerNonUserCodeAttribute()]
            protected TestDataSet(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) : 
                    base(info, context, false) {
                if ((this.IsBinarySerialized(info, context) == true)) {
                    this.InitVars(false);
                    System.ComponentModel.CollectionChangeEventHandler schemaChangedHandler1 = new System.ComponentModel.CollectionChangeEventHandler(this.SchemaChanged);
                    this.Tables.CollectionChanged += schemaChangedHandler1;
                    this.Relations.CollectionChanged += schemaChangedHandler1;
                    return;
                }
                string strSchema = ((string)(info.GetValue("XmlSchema", typeof(string))));
                if ((this.DetermineSchemaSerializationMode(info, context) == System.Data.SchemaSerializationMode.IncludeSchema)) {
                    System.Data.DataSet ds = new System.Data.DataSet();
                    ds.ReadXmlSchema(new System.Xml.XmlTextReader(new System.IO.StringReader(strSchema)));
                    if ((ds.Tables["member"] != null)) {
                        base.Tables.Add(new memberDataTable(ds.Tables["member"]));
                    }
                    this.DataSetName = ds.DataSetName;
                    this.Prefix = ds.Prefix;
                    this.Namespace = ds.Namespace;
                    this.Locale = ds.Locale;
                    this.CaseSensitive = ds.CaseSensitive;
                    this.EnforceConstraints = ds.EnforceConstraints;
                    this.Merge(ds, false, System.Data.MissingSchemaAction.Add);
                    this.InitVars();
                }
                else {
                    this.ReadXmlSchema(new System.Xml.XmlTextReader(new System.IO.StringReader(strSchema)));
                }
                this.GetSerializationData(info, context);
                System.ComponentModel.CollectionChangeEventHandler schemaChangedHandler = new System.ComponentModel.CollectionChangeEventHandler(this.SchemaChanged);
                base.Tables.CollectionChanged += schemaChangedHandler;
                this.Relations.CollectionChanged += schemaChangedHandler;
            }
            
            [System.Diagnostics.DebuggerNonUserCodeAttribute()]
            [System.ComponentModel.Browsable(false)]
            [System.ComponentModel.DesignerSerializationVisibility(System.ComponentModel.DesignerSerializationVisibility.Content)]
            public memberDataTable member {
                get {
                    return this.tablemember;
                }
            }
            
            [System.Diagnostics.DebuggerNonUserCodeAttribute()]
            [System.ComponentModel.BrowsableAttribute(true)]
            [System.ComponentModel.DesignerSerializationVisibilityAttribute(System.ComponentModel.DesignerSerializationVisibility.Visible)]
            public override System.Data.SchemaSerializationMode SchemaSerializationMode {
                get {
                    return this._schemaSerializationMode;
                }
                set {
                    this._schemaSerializationMode = value;
                }
            }
            
            [System.Diagnostics.DebuggerNonUserCodeAttribute()]
            [System.ComponentModel.DesignerSerializationVisibilityAttribute(System.ComponentModel.DesignerSerializationVisibility.Hidden)]
            public new System.Data.DataTableCollection Tables {
                get {
                    return base.Tables;
                }
            }
            
            [System.Diagnostics.DebuggerNonUserCodeAttribute()]
            [System.ComponentModel.DesignerSerializationVisibilityAttribute(System.ComponentModel.DesignerSerializationVisibility.Hidden)]
      

  6.   

    public new System.Data.DataRelationCollection Relations {
                get {
                    return base.Relations;
                }
            }
            
            [System.Diagnostics.DebuggerNonUserCodeAttribute()]
            protected override void InitializeDerivedDataSet() {
                this.BeginInit();
                this.InitClass();
                this.EndInit();
            }
            
            [System.Diagnostics.DebuggerNonUserCodeAttribute()]
            public override System.Data.DataSet Clone() {
                TestDataSet cln = ((TestDataSet)(base.Clone()));
                cln.InitVars();
                cln.SchemaSerializationMode = this.SchemaSerializationMode;
                return cln;
            }
            
            [System.Diagnostics.DebuggerNonUserCodeAttribute()]
            protected override bool ShouldSerializeTables() {
                return false;
            }
            
            [System.Diagnostics.DebuggerNonUserCodeAttribute()]
            protected override bool ShouldSerializeRelations() {
                return false;
            }
            
            [System.Diagnostics.DebuggerNonUserCodeAttribute()]
            protected override void ReadXmlSerializable(System.Xml.XmlReader reader) {
                if ((this.DetermineSchemaSerializationMode(reader) == System.Data.SchemaSerializationMode.IncludeSchema)) {
                    this.Reset();
                    System.Data.DataSet ds = new System.Data.DataSet();
                    ds.ReadXml(reader);
                    if ((ds.Tables["member"] != null)) {
                        base.Tables.Add(new memberDataTable(ds.Tables["member"]));
                    }
                    this.DataSetName = ds.DataSetName;
                    this.Prefix = ds.Prefix;
                    this.Namespace = ds.Namespace;
                    this.Locale = ds.Locale;
                    this.CaseSensitive = ds.CaseSensitive;
                    this.EnforceConstraints = ds.EnforceConstraints;
                    this.Merge(ds, false, System.Data.MissingSchemaAction.Add);
                    this.InitVars();
                }
                else {
                    this.ReadXml(reader);
                    this.InitVars();
                }
            }
            
            [System.Diagnostics.DebuggerNonUserCodeAttribute()]
            protected override System.Xml.Schema.XmlSchema GetSchemaSerializable() {
                System.IO.MemoryStream stream = new System.IO.MemoryStream();
                this.WriteXmlSchema(new System.Xml.XmlTextWriter(stream, null));
                stream.Position = 0;
                return System.Xml.Schema.XmlSchema.Read(new System.Xml.XmlTextReader(stream), null);
            }
            
            [System.Diagnostics.DebuggerNonUserCodeAttribute()]
            internal void InitVars() {
                this.InitVars(true);
            }
            
            [System.Diagnostics.DebuggerNonUserCodeAttribute()]
            internal void InitVars(bool initTable) {
                this.tablemember = ((memberDataTable)(base.Tables["member"]));
                if ((initTable == true)) {
                    if ((this.tablemember != null)) {
                        this.tablemember.InitVars();
                    }
                }
            }
            
            [System.Diagnostics.DebuggerNonUserCodeAttribute()]
            private void InitClass() {
                this.DataSetName = "TestDataSet";
                this.Prefix = "";
                this.Namespace = "http://tempuri.org/TestDataSet.xsd";
                this.EnforceConstraints = true;
                this.SchemaSerializationMode = System.Data.SchemaSerializationMode.IncludeSchema;
                this.tablemember = new memberDataTable();
                base.Tables.Add(this.tablemember);
            }
            
            [System.Diagnostics.DebuggerNonUserCodeAttribute()]
            private bool ShouldSerializemember() {
                return false;
            }
            
            [System.Diagnostics.DebuggerNonUserCodeAttribute()]
            private void SchemaChanged(object sender, System.ComponentModel.CollectionChangeEventArgs e) {
                if ((e.Action == System.ComponentModel.CollectionChangeAction.Remove)) {
                    this.InitVars();
                }
            }
            
            [System.Diagnostics.DebuggerNonUserCodeAttribute()]
            public static System.Xml.Schema.XmlSchemaComplexType GetTypedDataSetSchema(System.Xml.Schema.XmlSchemaSet xs) {
                TestDataSet ds = new TestDataSet();
                System.Xml.Schema.XmlSchemaComplexType type = new System.Xml.Schema.XmlSchemaComplexType();
                System.Xml.Schema.XmlSchemaSequence sequence = new System.Xml.Schema.XmlSchemaSequence();
                xs.Add(ds.GetSchemaSerializable());
                System.Xml.Schema.XmlSchemaAny any = new System.Xml.Schema.XmlSchemaAny();
                any.Namespace = ds.Namespace;
                sequence.Items.Add(any);
                type.Particle = sequence;
                return type;
            }
            
            public delegate void memberRowChangeEventHandler(object sender, memberRowChangeEvent e);
            
            [System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "2.0.0.0")]
            [System.Serializable()]
            [System.Xml.Serialization.XmlSchemaProviderAttribute("GetTypedTableSchema")]
            public partial class memberDataTable : System.Data.DataTable, System.Collections.IEnumerable {
                
                private System.Data.DataColumn columnid;
                
                private System.Data.DataColumn columnname;
                
                private System.Data.DataColumn columnworkid;
                
                [System.Diagnostics.DebuggerNonUserCodeAttribute()]
                public memberDataTable() {
                    this.TableName = "member";
                    this.BeginInit();
                    this.InitClass();
                    this.EndInit();
                }
                
                [System.Diagnostics.DebuggerNonUserCodeAttribute()]
                internal memberDataTable(System.Data.DataTable table) {
                    this.TableName = table.TableName;
                    if ((table.CaseSensitive != table.DataSet.CaseSensitive)) {
                        this.CaseSensitive = table.CaseSensitive;
                    }
                    if ((table.Locale.ToString() != table.DataSet.Locale.ToString())) {
                        this.Locale = table.Locale;
                    }
                    if ((table.Namespace != table.DataSet.Namespace)) {
                        this.Namespace = table.Namespace;
                    }
                    this.Prefix = table.Prefix;
                    this.MinimumCapacity = table.MinimumCapacity;
                }
                
                [System.Diagnostics.DebuggerNonUserCodeAttribute()]
                protected memberDataTable(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) : 
                        base(info, context) {
                    this.InitVars();
                }
                
                [System.Diagnostics.DebuggerNonUserCodeAttribute()]
                public System.Data.DataColumn idColumn {
                    get {
                        return this.columnid;
                    }
                }
                
                [System.Diagnostics.DebuggerNonUserCodeAttribute()]
                public System.Data.DataColumn nameColumn {
                    get {
                        return this.columnname;
                    }
                }
                
                [System.Diagnostics.DebuggerNonUserCodeAttribute()]
                public System.Data.DataColumn workidColumn {
                    get {
                        return this.columnworkid;
                    }
                }
                
                [System.Diagnostics.DebuggerNonUserCodeAttribute()]
                [System.ComponentModel.Browsable(false)]
                public int Count {
                    get {
                        return this.Rows.Count;
                    }
                }
                
                [System.Diagnostics.DebuggerNonUserCodeAttribute()]
      

  7.   

    代码太多了,我就不看了,这个实现起来不难...不过如果你要用CommandBuilder的话,有几个限制条件,其中两条是你数据库中的表有主键,另外只针对单表操作...如果你装有MSDN的话,你去看看这个例子:
    ms-help://MS.MSDNQTR.v80.chs/MS.MSDN.v80/MS.VisualStudio.v80.chs/dv_fxmclictl/html/1660f69c-5711-45d2-abc1-e25bc6779124.htm
      

  8.   

    如果没装MSDN,我把例子给你贴出来...using System;
    using System.Data;
    using System.Data.SqlClient;
    using System.Windows.Forms;public class Form1 : System.Windows.Forms.Form
    {
        private DataGridView dataGridView1 = new DataGridView();
        private BindingSource bindingSource1 = new BindingSource();
        private SqlDataAdapter dataAdapter = new SqlDataAdapter();
        private Button reloadButton = new Button();
        private Button submitButton = new Button();    [STAThreadAttribute()]
        public static void Main()
        {
            Application.Run(new Form1());
        }    // Initialize the form.
        public Form1()
        {
            dataGridView1.Dock = DockStyle.Fill;        reloadButton.Text = "reload";
            submitButton.Text = "submit";
            reloadButton.Click += new System.EventHandler(reloadButton_Click);
            submitButton.Click += new System.EventHandler(submitButton_Click);        FlowLayoutPanel panel = new FlowLayoutPanel();
            panel.Dock = DockStyle.Top;
            panel.AutoSize = true;
            panel.Controls.AddRange(new Control[] { reloadButton, submitButton });        this.Controls.AddRange(new Control[] { dataGridView1, panel });
            this.Load += new System.EventHandler(Form1_Load);
            this.Text = "DataGridView databinding and updating demo";
        }    private void Form1_Load(object sender, System.EventArgs e)
        {
            // Bind the DataGridView to the BindingSource
            // and load the data from the database.
            dataGridView1.DataSource = bindingSource1;
            GetData("select * from Customers");
        }    private void reloadButton_Click(object sender, System.EventArgs e)
        {
            // Reload the data from the database.
            GetData(dataAdapter.SelectCommand.CommandText);
        }    private void submitButton_Click(object sender, System.EventArgs e)
        {
            // Update the database with the user's changes.
            dataAdapter.Update((DataTable)bindingSource1.DataSource);
        }    private void GetData(string selectCommand)
        {
            try
            {
                // Specify a connection string. Replace the given value with a 
                // valid connection string for a Northwind SQL Server sample
                // database accessible to your system.
                String connectionString =
                    "Integrated Security=SSPI;Persist Security Info=False;" +
                    "Initial Catalog=Northwind;Data Source=localhost";            // Create a new data adapter based on the specified query.
                dataAdapter = new SqlDataAdapter(selectCommand, connectionString);            // Create a command builder to generate SQL update, insert, and
                // delete commands based on selectCommand. These are used to
                // update the database.
                SqlCommandBuilder commandBuilder = new SqlCommandBuilder(dataAdapter);            // Populate a new data table and bind it to the BindingSource.
                DataTable table = new DataTable();
                table.Locale = System.Globalization.CultureInfo.InvariantCulture;
                dataAdapter.Fill(table);
                bindingSource1.DataSource = table;            // Resize the DataGridView columns to fit the newly loaded content.
                dataGridView1.AutoResizeColumns( 
                    DataGridViewAutoSizeColumnsMode.AllCellsExceptHeader);
            }
            catch (SqlException)
            {
                MessageBox.Show("To run this example, replace the value of the " +
                    "connectionString variable with a connection string that is " +
                    "valid for your system.");
            }
        }}
      

  9.   

    這個論壇不能貼附件嗎,代碼太多了,貼了好幾次都沒貼完
    樓上的大哥我是這樣做的,就是在visual studio 2005中用數據源中的數據拖到一個form裏面然後它就自動生成了這個DataGridView,然後還有那些按鈕,不過在調試的時候刪除和更新數據都會出現錯誤,請指教,謝謝!