Salman  Mushtaq

Salman Mushtaq

  • NA
  • 45
  • 32.4k

Data Adapter

Dec 13 2013 3:38 PM
I have a database names database1 and i am using Vistual Stdio 2012 , I create a connection and fill table from database through SqlDataAdapter Object using fill method , then i create a row in (in-memory database) and insert data in that row through parameterized query and add these patameters in data adapter like
dataadapter.Parameters.Add(Parameter name) ;
and finally update the database through Update method
all code is wroking but Update method is not working and data cannot insert into actual data base 
here is my code

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Threading.Tasks; 
using System.Data.SqlClient; 
using System.Data; 

namespace ConsoleApplication3 

class Program 

static void Main(string[] args) 

string cs = @"Data Source=(LocalDB)\v11.0;AttachDbFilename=E:\EAD\ConsoleApplication3\ConsoleApplication3\Database1.mdf;Integrated Security=True"; 
SqlConnection con = new SqlConnection(cs); 
string q = "Select * from Student"; 
SqlCommand cmd = new SqlCommand(q, con); 
con.Open(); 
SqlDataAdapter da = new SqlDataAdapter(); 
DataTable t = new DataTable("t"); 
da.SelectCommand = cmd; 
da.Fill(t); 
foreach (DataRow r in t.Rows) 

Console.Write("Id = " + r[0]+" "); 
Console.Write("Name = " + r[1]+" "); 
Console.WriteLine("Cgpa = " + r[2]); 


//Add new Row 



string q1 = "Insert into Student (Id,Name,Cgpa) value (@I,@N,@C) "; 
Console.WriteLine("Insert ki query sahi chal rahi hai"); 

SqlCommand cmd1 = new SqlCommand(q1, con); 
 
SqlParameter p1 = new SqlParameter("I",SqlDbType.Variant,50,"Id"); 

SqlParameter p2 = new SqlParameter("N", SqlDbType.VarChar, 50, "Name"); 

SqlParameter p3 = new SqlParameter("C", SqlDbType.VarChar, 50, "Cgpa"); 

cmd1.Parameters.Add(p1); 

cmd1.Parameters.Add(p2); 

cmd1.Parameters.Add(p3); 

da.InsertCommand = cmd1; 

DataRow r1 = t.NewRow(); 
r1[0] = 15; 
r1[1] = "Ahmad"; 
r1[2] = "6.7"; 
t.Rows.Add(r1); 





da.Update(t); 

con.Close(); 


} 

There is exception , kindly explain the reason behind this .
Regards
Salman Muhtaq
Pakistan

Answers (4)