通过向导VisualStudio断开连接的DataSet

时间:2013-04-11 19:54:07

标签: c# sql visual-studio-2012

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

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();

            }

        }
    }
}

提前致谢:)

1 个答案:

答案 0 :(得分:0)

我发现了问题,第三个命令行应该是: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();
  }