Updating DataTable In DataBase Using SqlDataAdapter
Sep 4, 2007
Hi Guys
I am facing a problem while updating a DataTable to database using sqldataadapter.
In my application I am fetching a dataTable from Database and filling values into textboxes on the UI.
User has given facility to change or add new texboxes (new row) on the fly .
(Textboxes on the UI are like in a row(tr) having two textboxes in each row.)
I am again then converting a new (empty) datatable from scrap and filling its rows with the value of textboxes on submit button event.
The datatable which I have created has the same schema as the database table.
Now what I want here is that changed value should be reflected to the already existed rows in database and only new rows should be inserted.
I am using a SQLDataAdapter having two sqlcommands , one for update with update procedure name and parameter mapping and another for insert with parameter mapping.
But SqlDataAdapter is inserting fresh new rows all the time in the database table not updating the older one.
Please help me in the matter
Thanks & Regards
Vishal Sharma
View 2 Replies
ADVERTISEMENT
Jan 8, 2008
I am quite new to ASP.net 2.0. I have had plenty of experience using ADO.net in standard windows applications.
In my app I am opening a connection to an SQL database and I am creating a DataTable without a DataSet:
Shared m_cnADONetConnection As New System.Data.SqlClient.SqlConnection
Shared m_daDataAdapter As System.Data.SqlClient.SqlDataAdapter
Shared m_rowPosition As Integer
Shared m_dtContacts As New System.Data.DataTable
I am initializing everything and filling my DataTable when the Page first Loads if it isnt a postback.Protected Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Form1.Load
If Not Page.IsPostBack Then
m_rowPosition = 0
m_cnADONetConnection.ConnectionString = "Data Source=.SQLEXPRESS;AttachDbFilename=C:First ASP DatabaseApp_DataMyFirstDatabase.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True"
m_cnADONetConnection.Open()m_daDataAdapter = New System.Data.SqlClient.SqlDataAdapter("Select * From Books", m_cnADONetConnection)m_cbRefillCommand = New System.Data.SqlClient.SqlCommand
m_daDataAdapter.Fill(m_dtContacts)
Me.ShowCurrentRecord()
End IfEnd Sub
The Me.ShowCurrentRecord Sub assigns the values of the current record(row) in the DataTable via (m_rowPosition) to TextBox controls on the form:
I also have record navigation buttons on my form: << < > >> Moving me from record to record (row to row) by incrementing or decrementing m_rowPosition
All is good! I am able navigate the DataTable and the textboxes change their text properties accordingly from record to record.
The only other control on my form is a button which I'm coding its click event to save changes that I made to the current row (record) by changing the values in the textboxes then clicking save.
Here is my code:Protected Sub ButtonSave_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles ButtonSave.Click
If m_dtContacts.Rows.Count <> 0 Then
m_dtContacts.Rows(m_rowPosition).BeginEdit()m_dtContacts.Rows(m_rowPosition)("Title") = TBTitle.Text
m_dtContacts.Rows(m_rowPosition)("Author") = TBAuthor.Textm_dtContacts.Rows(m_rowPosition)("YearPublished") = TBYearPublished.Text
m_dtContacts.Rows(m_rowPosition)("Price") = TBPrice.Textm_dtContacts.Rows(m_rowPosition)("LastReadOn") = TBLastReadOn.Textm_dtContacts.Rows(m_rowPosition)("PageCount") = TBPageCount.Text
m_dtContacts.Rows(m_rowPosition).AcceptChanges()
m_dtContacts.Rows(m_rowPosition).EndEdit()
m_dtContacts.AcceptChanges()
m_daDataAdapter.Update(m_dtContacts)
End Sub
After I click save I can navigate through my records and back to the one I just changed and updated and all is well. The changes were made in the table.
However, when I close the page and exit out of Visual Web Developer and reopen the database: THE CHANGES WERENT UPDATED!!!
This worked all the time in VB2005.net when developing a standard windows app.
Can I use the same approach I was using in my code above or am I missing something.
I have read and searched all over and what I'm thinking is that my UpdateCommand, InsertCommand, DeleteCommand, SelectCommand are empty.
Do I have to do it this way?
View 1 Replies
View Related
Feb 20, 2008
Hi, I was looking at how to update a database using SqlDataAdapter and I stumbled upon this code snippet from (http://www.java2s.com/Code/CSharp/Database-ADO.net/UpdatedatabaseusingtheSqlDataAdapter.htm):using System;
using System.Data;
using System.Data.SqlClient;
class Class1{
static void Main(string[] args){
SqlConnection thisConnection = new SqlConnection("server=(local)\SQLEXPRESS;database=MyDatabase;Integrated Security=SSPI");
SqlDataAdapter thisAdapter = new SqlDataAdapter("SELECT ID, FirstName FROM Employee", thisConnection);
SqlCommandBuilder thisBuilder = new SqlCommandBuilder(thisAdapter);
DataSet thisDataSet = new DataSet();
thisAdapter.Fill(thisDataSet, "Employee");
Console.WriteLine("name before change: {0}", thisDataSet.Tables["Employee"].Rows[9]["FirstName"]);
thisDataSet.Tables["Employee"].Rows[1]["FirstName"] = "Inc";
thisAdapter.Update(thisDataSet, "Employee");
Console.WriteLine("name after change: {0}", thisDataSet.Tables["Employee"].Rows[9]["FirstName"]);
}
}I was just wondering, without iteration, how did the line "thisDataSet.Tables["Employee"].Rows[1]["FirstName"] = "Inc";" managed to know which row it is to update? I tried it on my own application and it worked fine.Any help to assist me in understanding this would be appreciated. Thanks
View 3 Replies
View Related
Sep 3, 2007
Filling a DataTable from SqlQuery : If SqlQuery returns some null values problem ocurrs with DataTable.
Is it possible using DataTable with some null values in it?
Thanks
View 2 Replies
View Related
Sep 16, 2007
Hi,
I got a problem regarding autoincremental Database Fields and DataTables. Using the technique to map the DataBase to an *.xsd file and trying to insert a Row into the table always results in this kind of error:Cannot insert explicit value for identity column in table 'Cars' when IDENTITY_INSERT is set to OFF.
This only happens when I set CarIDs properties AutoIncrement = true, AutoIncrementSeed = -1, AutoIncrementStep = -1. Having AutoIncrement = false, results in this error:Column 'CarID' does not allow nulls.
Do I missunderstand something, or do I need to change some parts? I would be glad if someone could help me and figure out what I am doing wrong.Thanks a lot have a nice weekend.Regards Johannes
View 1 Replies
View Related
May 3, 2005
Hi everybody,
I am using VB Webforms as my front end and MSDE 2000 as my back end. I am not able to drop a database after executing the following vb code on that database:
Dim vConnection As New SqlConnection(vConnectionString) Dim vAdapter As New SqlDataAdapter("SELECT party_type_code, party_type_name, party_type_imported" & _ " FROM Party_Type" & _ " ORDER BY party_type_name", vConnection) Dim vDataTable As New DataTable() vAdapter.Fill(vDataTable) vAdapter.Dispose() vConnection.Dispose()
On trying to drop the database using the SQL Command "DROP DATABASE PPCABCD2005", I get the error message:Cannot drop the database 'PPCABCD2005' because it is currently in use ...However, if I don't execute the above code, I am able to drop it. Why is it so? What is the solution to this problem?
View 2 Replies
View Related
Nov 18, 2005
Hi All!! I need to export a whole datatable to the database, through bulk insert or any other method..Can any body help me in that??Yes, col's in the database table and datatable are same!!Thx,Regards,Nilee..
View 4 Replies
View Related
May 12, 2008
I'm working with a legacy database whose structure I cannot change. I'm building a web-based editor for one of the DB's tables. This table has a Primary Key called "Master_Idx" that is an Identity (autonumber) field.To start, I query the DB and populate a data table which is cached. This is used to "feed" the web form. Any additions, changes, and deletions are reflected in this cached table.The user then has the flexibility to press Save at any time, which ensures that the database is modified accordingly.Here's my question:When new records are added, I assign them a Master_Idx value, the first of which was calculated to be 1 + the Max(Master_Idx) value when the editing session started. But when I insert these records back into the database it's possible that another user might have also been doing similar editing (of different records from the same table), so there's no guarantee that the Master_Idx values in the data table will be identical to those in the DB. When I insert a record from the cached table back into the DB, what technique can I use to check what value was assigned to the Master_Idx? If it's not the same as in the cached table then I need to update it locally in a few places.I hope all of this makes sense but if it doesn't then let me know and I'll explain it in another way.Robert W.
View 2 Replies
View Related
Dec 21, 2005
I am try to start with SQL BROKER service,
When I lunch from sql Management studio the following query, this don't finish never.
ALTER DATATABLE dbname SET ENABLE_BROKER
Where I am mistaking ?
View 11 Replies
View Related
Sep 30, 2007
hi
it looks like my thread has been deleted but I keep on asking.
When trying to connect to a table i a SQL2005 database in a vb.Net webapplication I get the following error message from the wizard:
"The wizard detected the following errors when configuring the data adapter "SqlDataAdapter1".
"Check" Generated SELECT Statement
"Check" Generated Mappings
"Warning" Generated INSERT Statement
There were errors configuring the data adapter
"Warning" Generated UPDATE Statement
There were errors configuring the data adapter
"Warning" Generated DELETE Statement
There were errors configuring the data adapter"
The same connection works fine in a vb6 application. I have seen other threads concerning this in this forum but I can't find any answers. Any ideas anyone?
ciao chris
View 2 Replies
View Related
May 11, 2007
Can someone provide a step by step tutorial for this? I'd like to safely update a database that is used for a website without much or any downtime.
View 1 Replies
View Related
Jan 30, 2007
I have my first small SQl Server 2005 database developed on my localserver and I have also its equivalent as an online database.I wish to update the local database (using and asp.net interface) andthen to upload the data (at least the amended data, but given thesmall size all data should be no trouble) to the online database.I think replication is the straight answer but I have no experience ofthis and I am wondering what else I might use which might be lesscomplicated. One solution is DTS (using SQL 2000 terms) but i am notsure if I can set this up (1) to overwrite existing tables and (2) notto seemingly remove identity attributes from fields set as identities.I know there are other possibilities but I would be glad of advice asto the likely best method for a small database updated perhaps onceweekly or at less frequent intervals,Best wishes, John Morgan
View 3 Replies
View Related
Aug 1, 2007
Hi,
How do I insert data that I have collected in a local database onto a table on my online ie hosted database which is on a different server?
At the moment I am just uploading all the data to the hosted DB but this is wasting bandwith as only a small percentage of data is actually selected and used.
I thought that if i used a local DB and then update the table on my hosted DB this would be much more efficient, but I am not sure how to write the SQL code to do this!
Do I do some kind of
INSERT INTO sample_table
SELECT xxx
FROM origanal_table
Or is it more complicated than this?
Thanks
View 6 Replies
View Related
Aug 16, 2006
Hi guys. Does anybody have any clue about how to create a class which inherits from SqlDataAdapter? I tried but looks like SqlDataAdapter is not inheritable. I would like to extend it with some custom method such as a method which fills a Dataset (used with a DataGrid) with the only few records to display per page (say 20) against the thousand records it might instead contain otherwise.Any workarounds? Many thanks in advance for your help.
View 1 Replies
View Related
Mar 26, 2007
Hi I am writing an app in flash which needs to hook up to MS SQL via asp.I need the code below to pass the var (ptodaysDate) to the sql statement. I can hard code it in and it works great but I really need to pass the var from flash.Pulling my hair out here, not much left to go.Any help greatly appreciated.---------------------------------------------- [WebMethod] public Schedule[] getSchedule(int ptodaysDate) { SqlDataAdapter adpt = new SqlDataAdapter("SELECT scheduleID, roomName, eventType,unitName,groupName,staffName,staffName2,theDate,theEnd FROM tb_schedule Where theDate >= @rtodaysDate", connString); SqlParameter rtodaysDate = new SqlParameter("@rtodaysDate", ptodaysDate); DataSet ds = new DataSet(); ArrayList al = new ArrayList(); adpt.Fill(ds); foreach (DataRow row in ds.Tables[0].Rows) { Schedule obj = new Schedule(); obj.scheduleID = (int)row["scheduleID"]; obj.roomName = (string)row["roomName"]; obj.eventType = (string)row["eventType"]; obj.unitName = (string)row["unitName"]; obj.groupName = (string)row["groupName"]; obj.staffName = (string)row["staffName"]; obj.staffName2 = (string)row["staffName2"]; obj.theDate = (string)row["theDate"]; obj.theEnd = (string)row["theEnd"]; al.Add(obj); } Schedule[] outArray = (Schedule[])al.ToArray(typeof(Schedule)); return outArray; } public class Schedule { public int scheduleID; public string roomName; public string eventType; public string unitName; public string groupName; public string staffName; public string staffName2; public string theDate; public string theEnd; }
View 2 Replies
View Related
Apr 25, 2007
It's a pretty basic question but I haven't been able to find any examples out there. I dimmed a dataadapter and would like to reuse later in my code (line 3 in the code below). What is the correct syntax to do this? Dim da As New SqlDataAdapter("SELECT * FROM myTable", conn)da.Fill(myDataTable)da.______ ("SELECT * FROM myTable2", conn)da.Fill(myDataTable2)
View 2 Replies
View Related
Aug 15, 2007
I'm working on a project to dynamically create PDFs with content from an SQL server. My current approach is to get the data I need into a DataSet using SqlDataAdapter, write the DataSet to a stream as XML, transform the XML into FO and then output a pdf using FOP. For some reason I get the following exception "System.NullReferenceException - Object reference not set to an instance of an object" when I try to set the SelectCommand property of my data adapter. Code for the project follows:Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load Dim con As SqlConnection Dim cmd As SqlCommand Dim IDlist As String Dim keyidary As Array Dim query As String Dim tempxml As Stream query = "*****query is valid and very long, so it's not included here*****" IDlist = Request.Form("chosenIDs") keyidary = Split(IDlist, ",") Dim makequery As New StringBuilder(query) For Each ID As String In keyidary makequery.Append(" OR (KeyID = '" & ID & "')") Next query = makequery.ToString() 'Response.Write(query) When uncommented this prints the query just fine 'Response.End() Try con = New SqlConnection con.ConnectionString = "****Connection String is valid****" cmd = New SqlCommand cmd.CommandText = query cmd.CommandType = CommandType.Text cmd.Connection = con Dim adpt As SqlDataAdapter adpt.SelectCommand = cmd 'Response.Write(query) When these are above or between the previous 2 statements, query is printed, 'Response.End() otherwise I get the error described above. Dim profiles As New DataSet adpt.Fill(profiles) profiles.WriteXml(tempxml) Dim step1 As XslTransform = New XslTransform Dim step2 As XslTransform = New XslTransform step1.Load(Server.MapPath("TransAttmpt1.xslt")) step2.Load(Server.MapPath("formatXML.xsl")) Dim xml, pdf As String xml = "profiles.xml" pdf = "Profiles.pdf" Dim temp2xml As New XPathDocument(tempxml) Response.Write(query) Response.End() Dim midstream As Stream Dim finalxml As StreamWriter = New StreamWriter(xml) step1.Transform(temp2xml, Nothing, midstream, Nothing) Dim xpathdoc2 As XPathDocument = New XPathDocument(midstream) step2.Transform(xpathdoc2, Nothing, finalxml, Nothing) GeneratePDF(xml, pdf) 'There's a lot more but it doesn't seem relevant now.... I'm somewhat at a loss on how to proceed and any help is very greatly appreciated.Thanks!
View 2 Replies
View Related
Oct 1, 2007
Hi all,
I have datatable having around 50 rows and 3 columns ID, Name and ExpVal, which is an expression columns,where the values can be any SQL functions Like REPLICATE(), SOUNDEX ( 'value' ) Or REVERSE ( 'value' ).....
i want to insert each row in that datatable like
INSERT INTO TAB1 ( ID, Name, ExpVal) VALUES (1, 'some name', SOUNDEX ( 'some name' ) )
so that the ExpVal will have value of the function ie inserted row look like
ID Name ExpVal1 some name S500 <--- Result of SOUNDEX ( 'some name' )
I'm using sqldatadapter to insert these values to the database
string sql = "INSERT INTO TAB1 (ID, Name, ExpVal)VALUES (@ID, @Name, @ExpVal) ";SqlDataAdapter sqlAdptr = new SqlDataAdapter();SqlCommand sqlCmd = new SqlCommand(sql, con);sqlCmd.parameters.Add("@ID", SqlDbType.Int, 0, "ID");sqlCmd.parameters.Add("@Name", SqlDbType.NVarChar, 200, "Name");sqlCmd.parameters.Add("@ExpVal", SqlDbType.VarChar, 100, "ExpVal");sqlAdptr.InsertCommand = sqlCmd;sqlAdptr.Update(dataTable);
This works fine, but the problem is, now the TAB1 contains
ID Name ExpVal1 some name 'SOUNDEX ( 'some name' )' instead of S500
Thatis the sql funtion is passed by SqlDataAdapter to database as a string and it is not executing while row is inserted to the table.Please provide what changes i have to make if i want SOUNDEX ( 'some name' ) to executed while data insertion take place
Thanks in advance
View 1 Replies
View Related
Jun 3, 2008
I'm getting a strange error with my dataadapter. Here's my code: using (SqlConnection conn = new SqlConnection(
ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString))
{
SqlDataAdapter da = new SqlDataAdapter("sprocCUSTOM", conn);
da.SelectCommand.Parameters.AddWithValue("@eventID", EventID);
conn.Open(); //open connection
DataSet ds = new DataSet();
da.Fill(ds);
gvAttendees.DataSource = ds;
gvAttendees.DataBind();
}This is the error I'm getting: Incorrect syntax near 'sprocCUSTOM'.But the error is highlighted at the line that reads "da.Fill(ds);"There's nothing wrong with the stored procedure either. It exists and works fine.
View 2 Replies
View Related
Feb 6, 2004
I am using SqlDataAdapter.Update(DataSet) to insert records into multiple tables in one call, but for some reason only first table was inserted.
Dim _cnn As New SqlConnection(ConfigurationSettings.AppSettings("ConnectionString"))
Dim _sql As String = "Select a,b FROM Table1;Select d, c From Table2;"
Dim _da As New SqlDataAdapter(_sql, _cnn)
Dim _sqlCmdBdr As New SqlCommandBuilder(_da)
Dim _ds As New DataSet
_da.Fill(_ds)
Dim _newrow1 As DataRow = _ds.Tables(0).NewRow
_newrow1("a") = "NewA"
_newrow1("b") = "NewB"
_ds.Tables(0).Rows.Add(_newrow1)
Dim _newrow2 As DataRow = _ds.Tables(1).NewRow
_newrow2("d") = "NewD"
_newrow2("c") = "NewC"
_ds.Tables(1).Rows.Add(_newrow2)
_da.Update(_ds)
new record inserted only into Table1, no new rows in Table2
Please advise!
Thanks
View 1 Replies
View Related
Jul 6, 2007
Hi,
I am porting an ASP.NET/C# application from Microsoft Access to SQL Server 2005. In my code I have a method that uses the DataAdapter class to open a table, read some values out of it which are stored, open a second table, read some additional data from it storing the data in the same structure as used before, then updating the first table with the combined data.
When I execute the dataAdapter.Update() method I get the following error:
"Dynamic SQL generation for the Update Command is not supported against a Select Command that does not return any key column information."
I am uncertain what this error is about. This code worked fine against Microsoft Access so it must be something different in how SQL Server works.
Can anyone tell me what this error is complaining about?
Many thanks!
Bob
View 1 Replies
View Related
Jul 1, 2004
I got thrown into a new project that is going to require me to update an SQL server database tables from an Access table on the backend of an Oracle database on another server. At the end of each day the Access dabase will be updated from the Oracle database.
What I need to do, is when the Access database is updated I need to have the table in the SQL database automaticaly updated. When a new record is added to the Access table I need the new record added to the SQL table. When a record is deleted in the Access table I need to keep that record in the SQL table and set a field to a value (such as 0). And when a record is updated in Access, have it updated in SQL.
Needless to say this is a bit out of my area and not sure how to accomplish this.
Any help is greatly appreciated.
View 2 Replies
View Related
Jul 27, 2006
i have sql 2005 installed on my personal machine, but our server has sql 2000 on it. the structure of my database was made on the server, but i'm not sure how to update the server copy from my local copy. when i try to export my data from my local machine to the server (or import from my local machine to the server), i get pre-execute errors.
roughly every other week, i'll need to be able to update the server version from my local version, so i'm trying to find the most efficient method. what is the best way to update a 2000 database from a 2005 database? it doesn't matter if i append or overwrite, but i do use identity fields. the error i get when trying to use the import/export wizard is:
- Pre-execute (Error)
Messages
Error 0xc0202009: Data Flow Task: An OLE DB error has occurred. Error code: 0x80040E21.
An OLE DB record is available. Source: "Microsoft SQL Native Client" Hresult: 0x80040E21 Description: "Multiple-step OLE DB operation generated errors. Check each OLE DB status value, if available. No work was done.".
(SQL Server Import and Export Wizard)
Error 0xc0202025: Data Flow Task: Cannot create an OLE DB accessor. Verify that the column metadata is valid.
(SQL Server Import and Export Wizard)
Error 0xc004701a: Data Flow Task: component "Destination 3 - ReleaseNotes" (202) failed the pre-execute phase and returned error code 0xC0202025.
(SQL Server Import and Export Wizard)
View 4 Replies
View Related
Mar 16, 2007
With MUCH help from this site and its users, I now know how to link a SqlCommand to a stored procedure:
What I don't know how to do, if it is possible, is to use a stored procedure with a SQLDataAdapter...
Here is the code as I am using, anyone have an idea on how to do this the right way?
' Define data objects
Dim conn As SqlConnection
Dim dataSet As New DataSet
Dim adapter As SqlDataAdapter
If ViewState("FooterDataSet") Is Nothing Then
' Read the connection string from Web.config
Dim connectionString As String = _
ConfigurationManager.ConnectionStrings( _
"Greensheet").ConnectionString
' Initialize connection
conn = New SqlConnection(connectionString)
' Create adapter
adapter = New SqlDataAdapter("SELECT * " & _
"FROM Table " & _
"WHERE (ID= " & intID & ")", conn)
' Fill the DataSet
adapter.Fill(dataSet, "Footer")
' Store the DataSet in view state
ViewState("FooterDataSet") = dataSet
Else
dataSet = ViewState("FooterDataSet")
End If
' Prepare the sort expression using the gridSortDirection and
' gridSortExpression properties
Dim sortExpression As String
If gridSortDirection = SortDirection.Ascending Then
sortExpression = gridSortExpression & " ASC"
Else
sortExpression = gridSortExpression & " DESC"
End If
' Sort the data
dataSet.Tables("Footer").DefaultView.Sort = sortExpression
' Bind the grid to the DataSet
footerGrid.DataSource = _
dataSet.Tables("Footer").DefaultView
footerGrid.DataBind()
View 1 Replies
View Related
Jul 13, 2007
Since my select command involves multiple tables, I manually write the insert command, proplating the SqlParameters as follows:
string insCmdText = "INSERT INTO itcac_alan.COURSE " + " ([COURSE_ID], [COURSE_NAME], [COURSE_NO], [BEGIN_DATE], [END_DATE], [CREATER]) " + " VALUES(@COURSE_ID, @COURSE_NAME, @COURSE_NO, @BEGIN_DATE, @END_DATE, @CREATER)";
SqlCommand insCmd = new SqlCommand(insCmdText, conn); insCmd.Parameters.Add("@COURSE_ID", SqlDbType.VarChar); insCmd.Parameters.Add("@COURSE_NAME", SqlDbType.VarChar); insCmd.Parameters.Add("@COURSE_NO", SqlDbType.VarChar); insCmd.Parameters.Add("@BEGIN_DATE", SqlDbType.DateTime); insCmd.Parameters.Add("@END_DATE", SqlDbType.DateTime); insCmd.Parameters.Add("@CREATER", SqlDbType.VarChar);
da.InsertCommand = insCmd; // da is a data adapter
However, as I use the preceding adapter to update the underlying database which in fact is based on a disconnected DataRow, an exception is thrown:
The parameterized query '(@COURSE_ID varchar(8000),@COURSE_NAME varchar(8000),@COURSE_NO ' expects the parameter '@COURSE_ID', which was not supplied.
The code I update the database is as follows:
DataRow newRow = sourceTable.NewRow(); //sourceTable is a DataTable whose data rows are populated with da (SqlDataAdpater) in the preceding code
// Populating the newRow
Hashtable newValues = new Hashtable();
.....................
foreach (DictionaryEntry entry in newValues) { // entry.Key is identical to a column name in the newRow newRow[(string)entry.Key] = (entry.Value == null ? DBNull.Value : entry.Value); }
sourceTable.Rows.Add(newRow);
adapter.SelectCommand.Connection.Open();
adapter.Update(sourceTable); // Exception is thrown here
adapter.SelectCommand.Connection.Close();
Please give me some directions to debug. It seems that the values of Columns withn DataRow cannot be fetched into the corresponding adapter.InsertCommand.Parameters by the adpater. (As I use SqlCommandBuilder to automatically generate insert command, the code above wroks rightly.)
Thanks a million.
Ricky.
View 2 Replies
View Related
Aug 14, 2007
I know there are loads of posts on this, but this just will not update. I have tried various forms of the code all to no avail. And now I'm ready to throw my PC out the window........
What am I doing wrong?
cheers Mike
Dim da As SqlDataAdapterDim dSetOrp As DataSet
oCn = New SqlConnection(db.m_ConnectionString)
oCn.Open()da = New SqlDataAdapter("Select * from contact WHERE conid = " & lngConId, oCn)
dSetOrp = New DataSet
da.Fill(dSetOrp, "locTable") ' Fill the DataSet.
dSetOrp.Tables(0).Rows(0)("ConSttDate") = dtEffDateDim myBuilder As SqlCommandBuilder = New SqlCommandBuilder(da)
myBuilder.GetUpdateCommand()
da.UpdateCommand = myBuilder.GetUpdateCommand()
lRows = da.Update(dSetOrp, "locTable")
View 2 Replies
View Related
Feb 7, 2008
MyCommand.Parameters.Add(new SqlParameter("@ConsultantName",SqlDbType.VarChar));
MyCommand.Parameters.Add(new SqlParameter("@Calls",SqlDbType.VarChar));
MyCommand.Parameters.Add(new SqlParameter("@PPC",SqlDbType.VarChar));
MyCommand.Parameters.Add(new SqlParameter("@Mth",SqlDbType.VarChar));
MyCommand.Parameters.Add(new SqlParameter("@DaysInMonth",SqlDbType.VarChar));
MyCommand.Parameters.Add(new SqlParameter("@Coach",SqlDbType.VarChar));
MyCommand.Parameters.Add(new SqlParameter("@Center",SqlDbType.VarChar));
MyCommand.Parameters.Add(new SqlParameter("@ProductValue",SqlDbType.VarChar));
MyCommand.Parameters.Add(new SqlParameter("@ObjectiveValue",SqlDbType.VarChar));
MyCommand.CommandType = CommandType.StoredProcedure;
MyCommand.CommandTimeout = 360;
try
{
SqlDataAdapter saveCenterCoaches = new SqlDataAdapter(MyCommand);
saveCenterCoaches.InsertCommand = MyCommand;
DataSet updateSet = finalSet.GetChanges(DataRowState.Added);
saveCenterCoaches.Update(updateSet.Tables[0]);
}
catch(Exception ex)
{
throw ex;
}
Iam getting "Procedure expects parameter @ConsultantName, which was not supplied."
I have consultantname and other parameters built in my datatable.
Is it the correct way of doing?
Can someone help.It is urgent.
View 5 Replies
View Related
Apr 28, 2006
Hello Dears;
I have an SqlDataAdapter which contains may queries. One query contians 3 query parameters as follows:
SELECT SUM(Amount) AS TotalFROM BoxesWHERE EntryDate BETWEEN @date1 AND @date2 AND Area=@Area
the query cannot be ran unless the queries parameters were provided. I have to access this query in code to add the parameters from controls. Is it possible to access it or use sqlDataSource instead?
Thanks alot
View 2 Replies
View Related
Sep 21, 2006
I'm trying to pass a querystring to an SqlDataAdapter object. To check if the query is a valid SELECT statement, I simply use a try-catch. But dispite the try-catch it still accepts valid INSERT statements. However, in the parameterlist of the SqlDataAdapter the required parameter is a Transact SQL SELECT statement or a stored procedure... Am I doing something wrong? Here is my code:try
{
my_conn = conn_open();
da = new SqlDataAdapter(query, my_conn);
da.Fill(result.resultDataset);
my_conn.Dispose();
}
catch (Exception e)
{
result.errMsg = "Database Error: " + e.Message;
result.success = false;
} Kehil
View 1 Replies
View Related
Aug 14, 2007
How to configure sqldatadapter with query like
"select name ,id from tlb1 where id in (select id from tlb2 where dept=@dept)"
Is the nested subquery is not allowed while configuring sqldaadapter?
Swati
View 1 Replies
View Related
Apr 1, 2008
How do i get the result 'puzzle' from the SQL and assign it to Integer and use it to compare with Request.Form ?
Protected Sub Page_Load(ByVal sender As Object, _
ByVal e As System.EventArgs) Handles Me.Load
Dim connString As String = _ ConfigurationManager.ConnectionStrings("Local_LAConnectionString1").ConnectionString
Dim strsql As String = _
"Select CustomerID,CustomerNo,dbo.LA_DEC(Passkey) as passcode,dbo.LA_DEC(PuzzleKey) As puzzle, PuzzleFlag, NickName from Customers Where CustomerNo = '" & myAccount & "'"
Using myConnection As New SqlConnection(connString) Dim myCommand As New SqlCommand(strsql, myConnection)
myConnection.Open()
Dim PuzzleDataSet As New DataSet
Dim PuzzleAdapter As New SqlDataAdapter(myCommand) // <---- Coding here
myConnection.Close()
End Using
End Sub
View 7 Replies
View Related
Mar 31, 2004
I have a block of code that does a Fill() with a DataAdapter, which seems to throw an exception if no values are returned. Then, when I try to bind the DataSet that gets filled, an error occurs, it doesn't even try to bind the column headers or anything.
This process seems to work fine when some rows are found, but it is not always guaranteed that the row count will always be > 0. The nice thing about using the Fill() function, is that it creates all my column headers automatically, so I was just wondering if there's a way to do a Fill() then a subsequent DataBind() to a DataGrid which would automatically format the columns even when no rows are found?
Here's a bit of the source.. if the last line finds no rows, it throws an exception ( I assume this is normal):
strSQL = "SELECT * FROM Prods";
cm.CommandText = strSQL;
da = new SqlDataAdapter( cm );
da.Fill(shelf);
Anyone got any ideas on how to fix this problem?
Brent
View 3 Replies
View Related
Feb 28, 2005
hello i have this query but the data adapter wont accept it
i get this error
syntax error or access violation
if i hardcode the @person parameter in query analyzier it works fine.
ex: @person = 33 hardcoded
but it doesnt work in data adapter either 33 or @person
can someone please help me out
SELECT m.title, m.movieID, a.personID, 'Actor', p.firstName + ' ' + p.lastName
FROM movieactors a, people p, movies m
WHERE a.personID = p.personID
AND a.movieID = m.movieID
and a.personid = @person
UNION
(SELECT m.title, m.movieID, a.personID, 'Director', p.firstName + ' ' + p.lastName
FROM moviedirectors a, people p, movies m
WHERE a.personID = p.personID
AND a.movieID = m.movieID
and a.personid = @person
UNION
(SELECT m.title, m.movieID, a.personID, 'Writer', p.firstName + ' ' + p.lastName
FROM moviewriters a, people p, movies m
WHERE a.personID = p.personID
AND a.movieID = m.movieID
and a.personid = @person
UNION
(SELECT m.title, m.movieID, a.personID, 'Cinematographer', p.firstName + ' ' + p.lastName
FROM moviecinematographers a, people p, movies m
WHERE a.personID = p.personID
AND a.movieID = m.movieID
and a.personid = @person
UNION
(SELECT m.title, m.movieID, a.personID, 'Producer', p.firstName + ' ' + p.lastName
FROM movieproducers a, people p, movies m
WHERE a.personID = p.personID
AND a.movieID = m.movieID
and a.personid = @person))));
View 2 Replies
View Related