繁体   English   中英

C#:无法使用DataGridView和SqlCeConnection更新数据库上的数据

[英]C# : Not Able to update data on database using DataGridView and SqlCeConnection

我尝试了一切。 无法修复并找到解决方法。

错误:缺少参数。 [a.update(t)命令上的[参数序数= 2];

技术:C#,Visual Studio 2008

    public partial class Doctor : Form
    {
    SqlCeConnection con = new SqlCeConnection("Data Source=C:\\Users\\user\\Documents\\Visual Studio 2008\\Projects\\DBConnectionCSharp\\DBConnectionCSharp\\DBTesting1.sdf");
    SqlCeCommand cmd;
    DataTable t = new DataTable();
    SqlCeDataAdapter a;
    DataSet ds;
    SqlCeCommandBuilder cam;


    public Doctor()
    {
        InitializeComponent();
        this.Visible = true;
        con.Open();
        cmd = con.CreateCommand();
        cam = new SqlCeCommandBuilder(a);
        cmd.CommandText = "update Doctor set Name=@p2 where ID=@p1";

    }

    private void Doctor_Load(object sender, EventArgs e)
    {
       using (a = new SqlCeDataAdapter("SELECT * FROM Doctor", con))
        {
            a.Fill(t);
            DoctorView.DataSource = t;

        }
        con.Close();
    }

    private void Save_Click(object sender, EventArgs e)
    {
        a.UpdateCommand = cmd;
        a.Update(t);
    }
}

我会尝试以这种方式更改您的代码,抱歉,但是现在无法测试...

public partial class Doctor : Form
{

    public Doctor()
    {
       InitializeComponent();
       // Remove all the code used to initialize the global objects here
    }

    private void Doctor_Load(object sender, EventArgs e)
    {
       // Open the connection just when needed, 
       // Initialize the adapter and fill the grid
       using(SqlCeConnection con = new SqlCeConnection(.....))
       {
            DataTable t = new DataTable();
            SqlCeDataAdapter a = new SqlCeDataAdapter("SELECT * FROM Doctor", con);
            a.Fill(t);
            DoctorView.DataSource = t;
       }
    }

    private void Save_Click(object sender, EventArgs e)
    {
       using(SqlCeConnection con = new SqlCeConnection(.....))
       {

            // Prepare again the adapter with a valid select command
            SqlCeDataAdapter a = new SqlCeDataAdapter("SELECT * FROM Doctor", con);

            // Force the building of the internal command objects of the adapter
            SqlCeCommandBuilder cb = new SqlCeCommandBuilder(a);

            // Recover the datatable from the datasource of the grid            
            DataTable t = DoctorView.DataSource as DataTable;

            // Update the table with DataRows changed, deleted or inserted
            a.Update(t);
       }
    }
}

暂无
暂无

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

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