|
Comments and Discussions
|
 |
|
 |
I was having trouble adding a record to a Access 2000 database with an autonumber field. Your solution with the Row Update event handler was just what I needed.
Thanks for sharing!
|
|
|
|
 |
Hello! I use it code, but it doesn't work correctly. The data stored in the database, but after the closing and opening, they are deleted. after I save the data, I open the database and see its, but after the opening of my application they do not exist. What would it be? Please help me. I don't know who else can i ask. Thanks
my code:
private void Companies_Load(object sender, EventArgs e)
{
conn=new OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|\data2.mdb");
adapt = new OleDbDataAdapter("SELECT * FROM Company", conn);
ds = new DataSet();
OleDbCommandBuilder cmdBuilder = new OleDbCommandBuilder(adapt);
adapt.DeleteCommand = cmdBuilder.GetDeleteCommand();
adapt.UpdateCommand = cmdBuilder.GetDeleteCommand();
adapt.InsertCommand = cmdBuilder.GetInsertCommand();
adapt.Fill(ds, "Company");
companyDataGridView.DataSource = ds.Tables["Company"];
}
private void button1_Click(object sender, EventArgs e)
{
DataRow dr = ds.Tables["Company"].NewRow();
dr["ID"] = Int32.Parse(iDTextBox.Text);
dr["Address"] = addressTextBox.Text;
dr["BankDetails"] = bankDetailsTextBox.Text;
dr["Name"] = nameTextBox.Text;
dr["Email"] = emailTextBox.Text;
dr["Site"] = siteTextBox.Text;
ds.Tables["Company"].Rows.Add(dr);
try
{
adapt.Update(ds, "Company");
ds.AcceptChanges();
conn.Close();
}
catch (Exception ex) {
MessageBox.Show(ex.Message);
}
}
|
|
|
|
 |
Hi there,
I have a parent and child table both of them have an Auto Number field as a primary key.
Ie Order - OrderID PK
OrderDetails - OrderDetailID PK, OrderID FK
I can update the "order" table no problems. it create an Order ID (i.e 2000)
But Order detail table it gives errors "INSERT INTO statement".. when i look at the underlying row values, it is saving the order ID= 2000 aginst the OrderDetailID and OrderID in order Detail table.
Can anyone help me.
Thanks
Jay
|
|
|
|
 |
Hi Ritter,
This is the one I searched for long time ; Thanks for this rare content.I want to do this with typed dataset.Is it possible ?.
I am having two tables : Offer and OfferItems.Both tables having Identity fields as primary keys Offer_ID and OfferItem_ID respectively. the field "OI_OfferID" in OfferItem table relates the parent column Offer_ID. I am using stored procedures and configured dataset with these tables with relationship. My SP for inserting Offer also returns Offer_ID as OUTPUT value.
While adding OfferItem row ,I am setting the relation with Offer table by SetParentRow () method .I am able see this relation until adapterOffer.update().after updating Offer table , new Offer_Id (say 5) created.If updating offerItem , it throws foreign key violated error (as it has 0 as OI_OfferID). Here the reference value is not updated.
How I Insert in this scenario?
Please rescue me .
With Regards,
Mathi
|
|
|
|
 |
Hi Mathi,
I am experiencing the same problem. I also have a typed dataset with two tables bound by a foreign key relationship. My code looks like this: ('ds' is my data set)
var offerRow = ds.Offer.AddOfferRow (...);
var offerItemRow = ds.OfferItem.NewOfferItemRow ();
offerItemRow.OfferRow = offerRow; // calls SetParentRow
ds.OfferItem.AddOfferItemRow (offerItemRow);
// offerItemRow.OfferRow evaluates to the correct row.
new OfferDataTableAdapter ().Update (ds.Offer); // works fine
// offerItemRow.OfferRow now evaluates to null.
new OfferItemDataTableAdapter ().Update (ds.OfferItem);
// the above fails with a foreign key constraint violation.
t appears as if the the first Update breaks the relationship and the offerItemRow no longer has an OfferRow. offerItemRow.OfferID evaluates to -1, same as before the call to Update. Thus it is not a surprise that the second Update fails.
So my questions is, why does the first Update break the relationship? Does anyone know how to fix this?
Thanks a bunch,
Sergey
|
|
|
|
 |
Hi Sergey,
I still struggling with this problem. Now, I am doing manual update.That is , In insert SP, we are returning the inserted record (select from table where id = SCOPE_IDENTITY).so, it fills the adapter with new record .Then, I get the parent Id and updating child record with parent Id. The problem is, it is not possible to do this more than one relationship (parent-child); if we have child for child table, it is too difficult to update those records.I knew, it is ugly of doing; But, don't know how to achieve this as per article .
Thanks,
Mathi.
|
|
|
|
 |
hi,
how can i use a stored procedure to delete a record.
secondly, i trying to fill a variable with the query "select sum(columnname) from tablename where columname2 = 'something'. How can this be done. Can it be done using a stored procedure and how? Thanks
|
|
|
|
 |
i have a table called suppliers where their supplierIDs(which is a primary key for the table)is auto generated for them..problem is after they register how will i let them know their supplierID.please help
|
|
|
|
 |
You have to concatenate two sql statements. One to insert the new record and the other to retrieve it. as shown below.
here is a sample:
"insert into tableName (column1,column2....)Values (value1,value2,......); select id from tableName where id= scope_identity"
last row inserted for that session is fetched by the where clause condition "SCOPE_IDENTITY"
Note the ";" after the insert statement it is very important
SPC Nigeria
Thanks.
|
|
|
|
 |
can i find a execute application about database in c# 2005?
|
|
|
|
|
 |
I cannot get past this error. I get this error when trying to update the row on the dataset of the parent table. Isn't the PK (in this case 'ID') suppose to get updated with the stored procedure? Does anyone know what I am missing here? Thanks.
-Hector Cervantes
GIS Dude
|
|
|
|
 |
I figured it out. I did not have the identity field set up correctly. I am using the SCOPE_IDENTITY() function instead of @@IDENTITY. Here is a copy of one of my procedures:
ALTER PROCEDURE [dbo].[proc_insertCall]
(@ID int output,
@SessionID varchar(36),
@DialedNumber varchar(10),
@ANI varchar(10),
@CPN varchar(10),
@CalledNumber varchar(10),
@DID varchar(10),
@TFN varchar(10),
@TotalTime varchar(10),
@IVRTime int,
@XferTime int,
@TTA int,
@CompCode char(1),
@EndState varchar(4),
@CallStart datetime,
@CallStop datetime,
@Lat float,
@Lon float,
@DialedNoANICount int,
@OrigTZ int,
@TermTZ int,
@NetworkID int,
@LocationID int,
@Zipcode varchar(10)
)
AS
INSERT INTO CallRecord (SessionID, DialedNumber, ANI, CPN, CalledNumber, DID, TFN, TotalTime, IVRTime, XferTime, TTA,
CompCode,
EndState,
CallStart,
CallStop,
Lat, Lon,
DialedNoANICount,
OrigTZ, TermTZ,
NetworkID, LocationID, Zipcode)
VALUES
(@SessionID, @DialedNumber, @ANI, @CPN, @CalledNumber, @DID, @TFN, @TotalTime, @IVRTime, @XferTime, @TTA,
@CompCode,
@EndState,
@CallStart,
@CallStop,
@Lat, @Lon,
@DialedNoANICount,
@OrigTZ, @TermTZ,
@NetworkID, @LocationID, @Zipcode)
SELECT SCOPE_IDENTITY()
-Hector Cervantes
GIS Dude
|
|
|
|
 |
and another code
you will change ID not ParameterDirection , you will look like another column
but be sure it not null when you define.
ALTER PROCEDURE [dbo].[proc_InsertMobile]
( @ID nvarchar(50),@BrandName nvarchar(50)
)
AS
Begin
Insert Into mobilespec(
ID,BrandName
)
Values (@ID,
@BrandName
)
RETURN @@ROWCOUNT
End
Goodluck
mai
|
|
|
|
 |
How can we update and delete data in multiple tables using the same technique??????? plz help me.
|
|
|
|
 |
This is a great code. but seems like you can use it only with stored procedure. I'm not using stored procedure but i'm directly using insertcommand with "Insert INTO" statement and adding the parameters. Now my problem is the ParentID in the child table are not getting updated and it shows 0 value. This is what i'm doing in code;
1. i'm creating datasets (I'm using Myadapter.MissingSchemaAction = MissingSchemaAction.AddWithKey)
2. then i'm setting the relationship as explained in the example.
3. then i'm adding new parent row.
4. add new child row and set the parent row
5. for updates as i mentioned i'm not using stored procedure but i'm using insertcommand with "Insert into" statement along with parameters. Now with child dataset, i'm setting parameter.SourceVersion = DataRowVersion.Current
for the ParentID colum.
when i trigger update method, the parentid filed in child table is updated with 0 value.
can you tell me what am i doing wrong?
any lead in this matter would be higly appreciated.
thanks.
|
|
|
|
 |
Have you check the autoincrement value to the primary key in parent table?
|
|
|
|
 |
Tell me ! how i can do it By VB.NET 2005
I Love VB.net
|
|
|
|
 |
Hello ,
I have a question related to physical creation of a new dataTable in a given dataBase(SQL Server).
The Table to be created in the database is allready created in a dataSet,but it doesn't exist in dabase.
As input I have :
database name +
the conection string to the server +
dataSet containing the table to be inserted in the database
Could you provide few lines in order to make this happen ?I don't want to manualy create the table, which allready exists in memory dataset.
cosmin
|
|
|
|
 |
While trying this guide, I found another prblem. It happens when the number generated from the database duplicates with the key already exists in the datatable. I'm thinking about giving a increment seed in the datatable, but it seems too dangerous and complicated. Do you have any idea??
There's a simple solution, it is you must immeditately update the database when you add a new row into the database.
-- modified at 13:59 Monday 29th May, 2006
|
|
|
|
 |
Your solution works cos autonumber in database starts from 1, and in dataset(datatable) it starts from 0 so there is no collision.
Maybe the best way is to set enforceconstrains to false before updating occurs. In this way you don't have to communicate with your database on each created row.
And always set AutoIncrement to true and AutoIncrementStep = 1
In older versions of VS there was chance of error if you fill your datatable and autonumber in database doesn't starts with 1 (let say 15) so you could create first 15 rows and on 16th you would get error while creating row. But this is solved in VS2005.
|
|
|
|
 |
here is the problem
if you have database with 2 tables (ParentChild) you can fill dataset via dataadapter's select command to filter rows in relation order you gave.
dataadapter will create one big table with columns from both tables in that order.
But when you have dataset with 2 tables (in relation) how can you select(filter) rows from it.
There is no: dataset.select("filter_expression_for_both_tables")
there is only: dataset.tables("Parent").select("filter_expression")
I know there is datarow.getparent (or getchild) rows but is there any other way?
|
|
|
|
 |
hi,
i am trying to insert recors that user enters at registration page of my application. i have taken help from this article but it is giving me errors like
System.Data.OleDb.OleDbException: Syntax error in INSERT INTO statement.
Line 108: customerDataAdapter.Update(ds,"Customer");
Line 109: loginDetailsDataAdapter.Update(ds,"LoginDetails");
Line 110: conn.Close();
Can any one help me out, what is wrong with this cod
My Code is
private void addRecords()
{
//Creating the Dataset object
DataSet ds = new DataSet();
OleDbConnection conn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\\CPMS.mdb");
conn.Open();
//Creating DataTable 'Customer' in the DataSet and the CustomerDataAdapter
OleDbDataAdapter customerDataAdapter = new
OleDbDataAdapter(new OleDbCommand("SELECT * FROM Customer",conn));
customerDataAdapter.RowUpdated += new
OleDbRowUpdatedEventHandler(customerDataAdapter_OnRowUpdate);
OleDbCommandBuilder customerCmdBuilder = new OleDbCommandBuilder(customerDataAdapter);
customerDataAdapter.FillSchema(ds,SchemaType.Source);
DataTable cTable = ds.Tables["Table"];
cTable.TableName = "Customer";
//Creating DataTable 'LoginDetails' in the DataSet and the LoginDetailsDataAdapter
OleDbDataAdapter loginDetailsDataAdapter = new
OleDbDataAdapter(new OleDbCommand("SELECT * FROM LoginDetails",conn));
OleDbCommandBuilder loginDetailsCmdBuilder = new OleDbCommandBuilder(loginDetailsDataAdapter);
loginDetailsDataAdapter.FillSchema(ds,SchemaType.Source);
cTable = ds.Tables["Table"];
cTable.TableName = "LoginDetails";
// Creating relatioship b/w tables
ds.Relations.Add(new DataRelation("ParentChild",
ds.Tables["Customer"].Columns["CustomerID"],
ds.Tables["LoginDetails"].Columns["CustomerID"]));
//Inserting Data
DataRow customerRow = ds.Tables["Customer"].NewRow();
customerRow["EmailAddress"] = "TextEmailAdd.Text";
customerRow["FirstName"] = "TextFName.Text";
customerRow["LastName"] = "TextLName.Text";
customerRow["Address"] = "TextAddress.Text";
customerRow["PostalCode"] = "TextPCode.Text";
ds.Tables["Customer"].Rows.Add(customerRow);
DataRow loginDetailsRow = ds.Tables["LoginDetails"].NewRow();
loginDetailsRow["Login"] = "TextLogin.Text";
loginDetailsRow["Password"] = "TextPass.Value";
loginDetailsRow["Type"] = "C";
loginDetailsRow.SetParentRow(customerRow);
ds.Tables["LoginDetails"].Rows.Add(loginDetailsRow);
// updating database with new values using DataAdapter
customerDataAdapter.Update(ds,"Customer");
loginDetailsDataAdapter.Update(ds,"LoginDetails");
conn.Close();
}
static void customerDataAdapter_OnRowUpdate(object sender, OleDbRowUpdatedEventArgs e)
{
OleDbCommand cCmd = new OleDbCommand ("SELECT@@IDENTITY",e.Command.Connection);
e.Row["CustomerID"] = cCmd.ExecuteScalar();
e.Row.AcceptChanges();
}
salman rafiq
|
|
|
|
 |
Hi
I am facing similar issue with my code. I know where the problem lies; but do not know the solution.
In dataset with have datarows numbered 0 onwards. When say 1st record is inserted in the table - say with ID = 1, then RowUpdated event is fired. we try to assign 1 to the primary key ; but there already is a datarow with that ID. Hence the problem.
If you have already got the solution to the problem, please share it with me.
Thanks
~jyo
|
|
|
|
 |
Hi,
Did you get this fixed?
Pl. let me know.
Thanks
Valli
|
|
|
|
 |
Hi!
I have a problem when inserting data to db. In a parent level, lets say A, INSERT goes fine, but when inserting records to the child table (lets say B), it crashes.
It seems to be so that first child record is stored fine, but the next one fails. Following error is shown: "Column 'CarID' is constrained to be unique. Value '17' is already present."
The first child record gets CarId = 17 and now it tries to store the next child record with the same CarId. Somehow CarId is not geting a new unique value (next one should be 18)...
Can anyone help with this???
green
|
|
|
|
 |
Hi Green,
Try to turn off the constrainsts during the Update operation. Just set the EnforceConstraints property in your dataset and you're done:
ds.EnforceConstraints = false;
da.Update(ds)
ds.EnforceConstraints = true;
Mauricio Ritter - Brazil
MSN: mauricioritter(atsign)hotmail.com
English is not my native language so, if you find any spelling erros in my posts, please let me know.
|
|
|
|
 |
Hi Mauricio,
Your advice was very helpfull! Now everything is working nicely.
-green
|
|
|
|
 |
hello,
The situation i am facing now i have tables A,B,C,D,E
parent table A .then its Child tables B & D .
and B relates C ,D relates E
each parent child relation 1 - n relation
all should have been insert in single operation
i use data relation & assigning set parent row .
it goes normal.when i try to insert in brand new table
it gets error "column constraint should be unique value 1 already present"
then i use
dataset.Enforeconstraint =false;
but it does not have error . but inserted wrong data for child tables(last record of parent table only)
so give me better solution
|
|
|
|
 |
Hi there,
Can any one show me how to use an .OCX file that was implemented on vb 6.0.
I want to use it on my C# code on vs.net 2005 win xp, here is a sample of methos that i want to use:
connect()
Login()
sendMAil()
but I can get these methods through the object instance of this class:
Higate e.g.
Higate hg = new Higate();
hg.connect();
hg.Login();
hg.sendMail();
help me please!!
Hola developers
-- modified at 1:45 Thursday 26th January, 2006
|
|
|
|
 |
Hi,
I have an issue in updating the Primary Key in the Parent table. I have set of three tables (Database SQL2000), where A is related to B and B is related to C. I have written a stored procedure which returns all the records in these tables and fill up a single DataSet. All these table have primary key which is an Identity Column. The dataset then populates the three grids in the client application. The users can add/update/delete the values in all the three tables and there is single save button to do the updates.
My problem here is when I add a row in the Parent table say A and then add new rows in the child table B. The new generated ID in the Parent table is not propagated to the row in the child table.
I am using the same code as described in the article but language I am using is VB.NET. I am using RowUpdated event to capture get the latest ID returned from the stored procedure as output parameter.
When I debug the application, I can retrieve the new ID in the RowUpdated event and set it back to the datarow:
e.Row.Item("ColumnName") = newID.
e.Row.AcceptChanges()
But these changes are not seen in the dataset. It still has same old ID but in the DEBUG mode the e.row has the new value.
Moreover, its an issue because the event arguments are passed as Byval and not as ByRef. i.e. I am not getting the actual reference to the DataRow.
Has anybody faced this problems before? Please help...
|
|
|
|
 |
Hi Mayur,
Did you manage to solve this problem as I am experiencing similar difficulties?
Regards,
Matthew.
|
|
|
|
 |
Remember if you use xxx.acceptchanges then the dataset thinks non of the records are changed. Hence if you call xxx.update(yyy) after that the dataset will not write anything to the database, since it'll check for for changed records before doing the actual update to the db.
Maybe that'll help,
erick
|
|
|
|
 |
Can anybody help if one type primary key data from text box instead of taking autonumeric in asp.net?
Example above was perfect for autonumeric but I am using input from text box.
Thanx
|
|
|
|
|
 |
i am getting error of type "Syntax error in INSEERT INTO statement" when i am running the source code provided here on my PC.PLZ help me with related suggestions & this error occurs at Update level of program.
plz help me how can i retreive multiple columns of datatable in OLEDB connection for a particular id.
|
|
|
|
 |
I'm also getting the same error PLZ help us
|
|
|
|
 |
Great Article! I am trying to add the following xml into a SQL server table with 3 fields (firstname, lastname, details) and query into a new dataset. Is that posible? So far, all my attempts encode the details xml node as if it was text. Any ideas? <customers> <customer> <firstname>Gerardo</firstname> <lastname>Zapata</lastname> <details> <lives>San Diego</lives><works>Poway</works> </details> </customer> <customer> <firstname>Raul</firstname> <lastname>Zapata</lastname> <details> <lives>Rosarito</lives><works>Rosarito</works> </details> </customer> </customers> Thank you for your assistance Gerardo
|
|
|
|
 |
Hi,
I need to use a generic data access. (Working with both Access 2000 and SQL Server 2000)
So, I declare:
dim myDataAdapter as IDataAdapter
'Here initialize myDataAdapter with OleDbDataAdapter or SQLDataAdapter
But in this case I can not use "RowUpdated" event on myDataAdapter. How can I use the event mechanism? If I specify the type in declaration, this code works as needed:
dim myDataAdapter as SqlDataAdapter
myDataAdapter = new SqlDataAdapter
AddHandler myDataAdapter.RowUpdated, New SqlRowUpdatedEventHandler(AddressOf OnRowUpdated)
|
|
|
|
 |
Does anyone know how to do this in Oracle 9i? Post a link/example or e-mail if you do! Thanks!
|
|
|
|
 |
Thank you Mauricio - I'm sure your article saved me lots of time!
If at first you don't succeed, give up - Homer Simpson
|
|
|
|
 |
As long as it's SQL 2000 wouldn’t it be better to use SCOPE_IDENTITY?
Good article!
|
|
|
|
 |
Yeah... it would be better, because if you have some triggers, the solution won't work. I didn't have time to update the article with the SCOPE_IDENTITY yet.
Mauricio Ritter - Brazil
MSN: mauricioritter(atsign)hotmail.com
English is not my native language so, if you find any spelling erros in my posts, please let me know.
|
|
|
|
 |
This is a larger problem! Using an event to get the newly inserted identity row may theoretically return you a different value, provided that in between of your insert and an event for row updated another user adds his data. This could theoretically happen. In order to be certain that you're getting your own identity you should really use SCOPE_IDENTITY() in a batch command. This means right after the insert command delimited by (;). VS2005 wizard makes this such as:
INSERT INTO table VALUES (@bla, @bla1);
SELECT bla, bla1 FROM table WHERE bla=SCOPE_IDENTITY()
|
|
|
|
 |
Hi!
Thanks for nice article. You shows in your example how to create one relation betweeen two tables, like this:
// Create the relationship between the two tables
oDS.Relations.Add(new DataRelation("ParentChild",
oDS.Tables["Orders"].Columns["OrderId"],
oDS.Tables["OrderDetails"].Columns["OrderId"]));
I have to create more relations from one parent table to multiple children tables, like this:
// Create the relationship between multiple tables
oDS.Relations.Add(new DataRelation("ParentChild_1",
oDS.Tables["Orders"].Columns["OrderId"],
oDS.Tables["OrderDetails_1"].Columns["OrderId"]));
oDS.Relations.Add(new DataRelation("ParentChild_2",
oDS.Tables["Orders"].Columns["OrderId"],
oDS.Tables["OrderDetails_2"].Columns["OrderId"]));
This is NOT working, only 1st relation will be added! Is this generally possible???
Please, help me, i can't find anything to solve this problem!
Thx
Dmitry
|
|
|
|
 |
I've the same problem
|
|
|
|
 |
Yes, possible and doable. I have a master table with 4-5 and use the same technique shown in the sample code in your post (both VS2002 and VS2003). Can't tell what the problem is with your code from the sample code provided. To help, I created a utility function "MakeTableRelationShips" that can make things a little easier to understand/debug.
public void MakeTableRelationship( string parentTableName,
string childTableName,
string linkColumnName )
{
//Existing relationship error checking removed.
//Get the needed tables.
DataTable parentTable = GetTable( parentTableName );
DataTable childTable = GetTable( childTableName );
//Get link columns.
DataColumn parentColumn = parentTable.Columns[ linkColumnName ];
DataColumn childColumn = childTable.Columns[ linkColumnName ];
//DataColumn error checking removed.
//Create the data relation.
string relationshipName = MakeRelationshipName( parentTableName,
childTableName );
DataRelation dataRelation = new DataRelation( relationshipName,
parentColumn,
childColumn );
//Add to the internal dataset.
try
{
_dataSet.Relations.Add( dataRelation );
}
#region Catch( InvalidConstraintException )
catch( InvalidConstraintException ice )
{
//Add your error logging here (mine is removed)
throw;
}
#endregion Catch( InvalidConstraintException )
}
Hope this helps (and isn't too late). Mike Lansdaal
|
|
|
|
 |
New to .Net, though I have a little experience in Classic ASP...
First, the Example was great, but my question is this
Why would I user a disconnected DataSet with Related Tables instead of just using sqlCommand Objects + Stored Procedures with Output Parameters that return The Identity of the Parent table?
Thanks in Advance
|
|
|
|
 |
I did not manage to get this working with MySQL (I used the Access version, without stored procedures.)
When I update I am getting an exception saying that I cannot update because I need an update command... something like that. I hate MySQL and I am tired today.
|
|
|
|
 |
|
|
General News Suggestion Question Bug Answer Joke Rant Admin
Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.
|
Type | Article |
Licence | |
First Posted | 15 Mar 2003 |
Views | 848,500 |
Bookmarked | 310 times |
|
|