断开连接的数据集由向导VisualStudio

本文关键字:向导 VisualStudio 数据集 连接 断开 | 更新日期: 2023-09-27 18:08:47

我使用向导来创建一个断开连接的数据集项目,但是,它允许我从表中更新和删除数据,但它不让我插入新的数据行,仍然给我消息框"SUCCESS" !!!!

namespace Disconnected_Database_by_Wizard
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        SqlConnection myConnection = new SqlConnection();
        SqlDataAdapter myAdapter = null;
        private void Form1_Load(object sender, EventArgs e)
        {
            myConnection.ConnectionString = "Server=CompileMe;Database=MyDataBase;Integrated Security = True";
            myAdapter = new SqlDataAdapter("Select * from MyList", myConnection);
            myConnection.Open();
            myAdapter.Fill(dataSet1,"MyList");
            SqlCommandBuilder myCommandBuilder = new SqlCommandBuilder(myAdapter);
            myAdapter.InsertCommand = myCommandBuilder.GetInsertCommand();
            myAdapter.UpdateCommand = myCommandBuilder.GetUpdateCommand();
            myAdapter.InsertCommand = myCommandBuilder.GetDeleteCommand();
        }
        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                myAdapter.Update(dataSet1 ,"Mylist");
                MessageBox.Show("Success");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
                myConnection.Close();
            }
        }
    }
}

提前感谢:)

断开连接的数据集由向导VisualStudio

我发现了问题,第三个命令行应该是:DeleteCommand而不是InsertCommand。

   { myAdapter.InsertCommand = myCommandBuilder.GetInsertCommand();
     myAdapter.UpdateCommand = myCommandBuilder.GetUpdateCommand();
      myAdapter.DeleteCommand = myCommandBuilder.GetDeleteCommand();
    }

代替:

  { myAdapter.InsertCommand = myCommandBuilder.GetInsertCommand();
    myAdapter.UpdateCommand = myCommandBuilder.GetUpdateCommand();
    myAdapter.InsertCommand = myCommandBuilder.GetDeleteCommand();
  }