简体   繁体   中英

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

I tried everything . Not able to fix and find the work around.

Error: A parameter is missing. [ Parameter ordinal = 2 ] on command a.update(t);

Technology : 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);
    }
}

I would try to change your code in this way, sorry but cannot test now...

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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