hola,

Buscando sobre el tema pude encontrar este codigo:
Que postearon en un pagina:

using System;


using System.Data;


using System.Data.SqlClient;





class MainClass


{


   static void Main(string[] args)


   {


      string connString = @"server = .\sqlexpress;integrated security = 
true;database = northwind";





      string qry = @"select * from employees where country = 'UK'";





      string ins = @"insert into 
employees(firstname,lastname,titleofcourtesy,city,country)


                                    
values(@firstname,@lastname,@titleofcourtesy,@city,@country)";





      SqlConnection conn = new SqlConnection(connString);





      try


      {


         SqlDataAdapter da = new SqlDataAdapter();


         da.SelectCommand = new SqlCommand(qry, conn);





         DataSet ds = new DataSet();


         da.Fill(ds, "employees");





         DataTable dt = ds.Tables["employees"];





         DataRow newRow = dt.NewRow();


         newRow["firstname"] = "R";


         newRow["lastname"] = "B";


         newRow["titleofcourtesy"] = "Sir";


         newRow["city"] = "B";


         newRow["country"] = "UK";


         dt.Rows.Add(newRow);





         foreach (DataRow row in dt.Rows)


         {


            Console.WriteLine(


               "{0} {1} {2}",


               row["firstname"].ToString().PadRight(15),


               row["lastname"].ToString().PadLeft(25),


               row["city"]);


         }





         SqlCommand cmd = new SqlCommand(ins, conn);


         cmd.Parameters.Add("@firstname",SqlDbType.NVarChar, 10,"firstname");


         cmd.Parameters.Add("@lastname",SqlDbType.NVarChar,20,"lastname");


         
cmd.Parameters.Add("@titleofcourtesy",SqlDbType.NVarChar,25,"titleofcourtesy");


         cmd.Parameters.Add("@city",SqlDbType.NVarChar,15,"city");


         cmd.Parameters.Add("@country",SqlDbType.NVarChar,15,"country");


         da.InsertCommand = cmd;


         da.Update(ds, "employees");


      }


      catch(Exception e)


      {


         Console.WriteLine("Error: " + e);


      }


      finally


      {


         conn.Close();


      }


   }


}

Algo que note es como vinculan el command con los campos del datarow.

Veras que en el codigo hace:
newRow["firstname"] = "R";


y debajo:
cmd.Parameters.Add("@firstname",SqlDbType.NVarChar, 10,"firstname");


O sea le indica que ese nombre de row se pasa en ese parametro del sql.

Has verificado que esta vinculacion este correcta ?

Saludos

--- El mar 5-may-09, Quique <[email protected]> escribió:
De: Quique <[email protected]>
Asunto: [puntonet] datagridview 2 way databinding
Para: [email protected]
Fecha: martes, 5 de mayo de 2009, 4:38 pm

Hola gente, estoy tratando de hacer 2 way databinding con 1 datagridview
(winforms, con vs 2008 express y sql 2008 express), tengo una tabla
"tarea" que sólo tiene id (con identity seed) y descripción.
Usé el ejemplo de la ayuda del vs....

El código para hacer el binding es este:

private void GetData() {
           SqlConnection cnn = new
SqlConnection("Server=(local)\\SQLEXPRESS;initial
catalog=db;Trusted_Connection=true;");
           SqlCommand command = new SqlCommand("select * from tarea",
cnn);
           SqlDataAdapter adapter = new SqlDataAdapter(command);
           SqlCommandBuilder builder = new SqlCommandBuilder(adapter);

           DataTable table = new DataTable();
           table.Locale = System.Globalization.CultureInfo.InvariantCulture;
           adapter.Fill(table);

           bindingSource1.DataSource = table;
}

Los datos los muestra bien en la datagridview, pero después de agregar alguna
fila cuando quiero hacer
   dataAdapter.Update((DataTable)bindingSource1.DataSource);

me da InvalidOperationException: "Update requires a valid InsertCommand
when passed DataRow collection with new rows." (abajo pongo todo)

(y lo mismo pasa cuando modifico con un mensaje casi igual)

El sqlbuilder parece estar funcionando bien porque si hago un
builder.GetInsertCommand(); me da un command con esto:
"INSERT INTO [tarea] ([descripcion]) VALUES (@p1)"

(el id es un identity con seed)

Alguien tiene idea cual es el problema o un link a un ejemplo de 2 way
databinding que funcione ?
Gracias,

Quique


System.InvalidOperationException was unhandled
 Message="Update requires a valid InsertCommand when passed DataRow
collection with new rows."
 Source="System.Data"
 StackTrace:
      at
System.Data.Common.DbDataAdapter.UpdatedRowStatusErrors(RowUpdatedEventArgs
rowUpdatedEvent, BatchCommandInfo[] batchCommands, Int32 commandCount)
      at System.Data.Common.DbDataAdapter.UpdatedRowStatus(RowUpdatedEventArgs
rowUpdatedEvent, BatchCommandInfo[] batchCommands, Int32 commandCount)
      at System.Data.Common.DbDataAdapter.Update(DataRow[] dataRows,
DataTableMapping tableMapping)
      at System.Data.Common.DbDataAdapter.UpdateFromDataTable(DataTable
dataTable, DataTableMapping tableMapping)
      at System.Data.Common.DbDataAdapter.Update(DataTable dataTable)
      at GestionTaller.TareasForm.butCerrar_Click(Object sender, EventArgs e)
in C:\desarrollo\GestionTaller\GestionTaller\TareasForm.cs:line
90
      at System.Windows.Forms.Control.OnClick(EventArgs e)
      at System.Windows.Forms.Button.OnClick(EventArgs e)
      at System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)
      at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons
button, Int32 clicks)
      at System.Windows.Forms.Control.WndProc(Message& m)
      at System.Windows.Forms.ButtonBase.WndProc(Message& m)
      at System.Windows.Forms.Button.WndProc(Message& m)
      at
System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
      at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message&
m)
      at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd,
Int32 msg, IntPtr wparam, IntPtr lparam)
      at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG&
msg)
      at
System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(Int32
dwComponentID, Int32 reason, Int32 pvLoopData)
      at
System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason,
ApplicationContext context)
      at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32
reason, ApplicationContext context)
      at System.Windows.Forms.Application.Run(Form mainForm)
      at GestionTaller.Program.Main() in
C:\desarrollo\GestionTaller\GestionTaller\Program.cs:line 18
      at System.AppDomain._nExecuteAssembly(Assembly assembly, String[] args)
      at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence
assemblySecurity, String[] args)
      at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
      at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
      at System.Threading.ExecutionContext.Run(ExecutionContext
executionContext, ContextCallback callback, Object state)
      at System.Threading.ThreadHelper.ThreadStart()
 InnerException:






      
____________________________________________________________________________________
¡Viví la mejor experiencia en la web!
Descargá gratis el nuevo Internet Explorer 8
http://downloads.yahoo.com/ieak8/?l=ar

Responder a