Search Results

Search found 45 results on 2 pages for 'insertcommand'.

Page 2/2 | < Previous Page | 1 2 

  • Failed to convert parameter value from a Guid to a String

    - by user320460
    Hello, I am at the end of my knowledge and googled for the answer too but no luck :/ Week ago everything worked well. I did a revert on the repository, recreated the tableadapter etc... nothing helped. When I try to save in my application I get an SystemInvalidCastException at this point: PersonListDataSet.cs: partial class P_GroupTableAdapter { public int Update(PersonListDataSet.P_GroupDataTable dataTable, string userId) { this.Adapter.InsertCommand.Parameters["@userId"].Value = userId; this.Adapter.DeleteCommand.Parameters["@userId"].Value = userId; this.Adapter.UpdateCommand.Parameters["@userId"].Value = userId; return this.Update(dataTable); **<-- Exception occurs here** } } Everything is stuck here because a Guid - and I checked the datatable preview with the magnifier tool its really a true Guid in the column of the datatable - can not be converted to a string ??? How can that happen?

    Read the article

  • why DbCommandBuilder (Oracle) produces weird WHERE-clause to UpdateCommand in C# / ADO.NET 2.0?

    - by matti
    I have a table HolidayHome in oracle db which has unique db index on Id (I haven't specified this in the code in any way for adapter/table/dataset, don't know if i should/can). DbDataAdapter.SelectCommand is like this: SELECT Id, ExtId, Label, Location1, Location2, Location3, Location4, ClassId, X, Y, UseType FROM HolidayHome but UpdateCommand generated by DbCommandBuilder has very weird where clause: UPDATE HOLIDAYHOME SET ID = :p1, EXTID = :p2, LABEL = :p3, LOCATION1 = :p4, LOCATION2 = :p5, LOCATION3 = :p6, LOCATION4 = :p7, CLASSID = :p8, X = :p9, Y = :p10, USETYPE = :p11 WHERE ((ID = :p12) AND ((:p13 = 1 AND EXTID IS NULL) OR (EXTID = :p14)) AND ((:p15 = 1 AND LABEL IS NULL) OR (LABEL = :p16)) AND ((:p17 = 1 AND LOCATION1 IS NULL) OR (LOCATION1 = :p18)) AND ((:p19 = 1 AND LOCATION2 IS NULL) OR (LOCATION2 = :p20)) AND ((:p21 = 1 AND LOCATION3 IS NULL) OR (LOCATION3 = :p22)) AND ((:p23 = 1 AND LOCATION4 IS NULL) OR (LOCATION4 = :p24)) AND (CLASSID = :p25) AND (X = :p26) AND (Y = :p27) AND (USETYPE = :p28)) the code is like this: static bool CreateInsertUpdateDeleteCmds(DbDataAdapter dataAdapter) { DbCommandBuilder builder = _trgtProvFactory.CreateCommandBuilder(); builder.DataAdapter = dataAdapter; // Get the insert, update and delete commands. dataAdapter.InsertCommand = builder.GetInsertCommand(); dataAdapter.UpdateCommand = builder.GetUpdateCommand(); dataAdapter.DeleteCommand = builder.GetDeleteCommand(); } what to do? The UpdateCommand is utter madness. Thanks & Best Regards: Matti

    Read the article

  • What do these .NET auto-generated table adapter commands do? e.g. UPDATE/INSERT followed by a SELECT

    - by RickL
    I'm working with a legacy application which I'm trying to change so that it can work with SQL CE, whilst it was originally written against SQL Server. The problem I am getting now is that when I try to do dataAdapter.Update, SQL CE complains that it is not expecting the SELECT keyword in the command text. I believe this is because SQL CE does not support batch SELECT statements. The auto-generated table adapter command looks like this... this._adapter.InsertCommand.CommandText = @"INSERT INTO [Table] ([Field1], [Field2]) VALUES (@Value1, @Value2); SELECT Field1, Field2 FROM Table WHERE (Field1 = @Value1)"; What is it doing? It looks like it is inserting new records from the datatable into the database, and then reading that record back from the database into the datatable? What's the point of that? Can I just go through the code and remove all these SELECT statements? Or is there an easier way to solve my problem of wanting to use these data adapters with SQL CE? I cannot regenerate these table adapters, as the people who knew how to have long since left.

    Read the article

  • why DbCommandBuilder (Oracle) produces weird WHERE-clause to UpdateCommand?

    - by matti
    I have a table HolidayHome in oracle db which has unique db index on Id (I haven't specified this in the code in any way for adapter/table/dataset, don't know if i should/can). DbDataAdapter.SelectCommand is like this: SELECT Id, ExtId, Label, Location1, Location2, Location3, Location4, ClassId, X, Y, UseType FROM HolidayHome but UpdateCommand generated by DbCommandBuilder has very weird where clause: UPDATE HOLIDAYHOME SET ID = :p1, EXTID = :p2, LABEL = :p3, LOCATION1 = :p4, LOCATION2 = :p5, LOCATION3 = :p6, LOCATION4 = :p7, CLASSID = :p8, X = :p9, Y = :p10, USETYPE = :p11 WHERE ((ID = :p12) AND ((:p13 = 1 AND EXTID IS NULL) OR (EXTID = :p14)) AND ((:p15 = 1 AND LABEL IS NULL) OR (LABEL = :p16)) AND ((:p17 = 1 AND LOCATION1 IS NULL) OR (LOCATION1 = :p18)) AND ((:p19 = 1 AND LOCATION2 IS NULL) OR (LOCATION2 = :p20)) AND ((:p21 = 1 AND LOCATION3 IS NULL) OR (LOCATION3 = :p22)) AND ((:p23 = 1 AND LOCATION4 IS NULL) OR (LOCATION4 = :p24)) AND (CLASSID = :p25) AND (X = :p26) AND (Y = :p27) AND (USETYPE = :p28)) all these fields that have like: ((:p17 = 1 AND LOCATION1 IS NULL) OR (LOCATION1 = :p18)) are defined in oracle db like this: LOCATION1 VARCHAR2(30) so they allow null values. the code looks like this: static bool CreateInsertUpdateDeleteCmds(DbDataAdapter dataAdapter) { DbCommandBuilder builder = _trgtProvFactory.CreateCommandBuilder(); builder.DataAdapter = dataAdapter; // Get the insert, update and delete commands. dataAdapter.InsertCommand = builder.GetInsertCommand(); dataAdapter.UpdateCommand = builder.GetUpdateCommand(); dataAdapter.DeleteCommand = builder.GetDeleteCommand(); } what to do? The UpdateCommand is utter madness. Thanks & Best Regards: Matti

    Read the article

  • What do these C# auto-generated table adapter commands do? e.g. UPDATE/INSERT followed by a SELECT

    - by RickL
    I'm working with a legacy application which I'm trying to change so that it can work with SQL CE, whilst it was originally written against SQL Server. The problem I am getting now is that when I try to do dataAdapter.Update, SQL CE complains that it is not expecting the SELECT keyword in the command text. I believe this is because SQL CE does not support batch SELECT statements. The auto-generated table adapter command looks like this... this._adapter.InsertCommand.CommandText = @"INSERT INTO [Table] ([Field1], [Field2]) VALUES (@Value1, @Value2); SELECT Field1, Field2 FROM Table WHERE (Field1 = @Value1)"; What is it doing? It looks like it is inserting new records from the datatable into the database, and then reading that record back from the database into the datatable? What's the point of that? Can I just go through the code and remove all these SELECT statements? Or is there an easier way to solve my problem of wanting to use these data adapters with SQL CE? I cannot regenerate these table adapters, as the people who knew how to have long since left.

    Read the article

  • How to create refresh statements for TableAdapter objects in Visual Studio?

    - by Mark Wilkins
    I am working on developing an ADO.NET data provider and an associated DDEX provider. I am unable to convince the Visual Studio TableAdapater Configuration Wizard to generate SQL statements to refresh the data table after inserts and updates. It generates the insert and delete statements but will not produce the select statements to do the refresh. The functionality referred to can be accessed by dropping a table from the Server Explorer (inside Visual Studio) onto a DataSet (e.g., DataSet1.xsd). It creates a TableAdapter object and configures SELECT, UPDATE, DELETE, and INSERT statements. If you right click on the TableAdapter object, the context menu has a “Configure” option that starts the “TableAdapter Configuration Wizard”. The first dialog of that wizard has an Advanced Options button, which leads to an option titled “Refresh the data table”. When used with SQL Server tables, that option causes a statement of the form “select field1, field2, …” to be added on to the end of the commands for the TableAdapter’s InsertCommand and UpdateCommand. Do you have any idea what type property or interface might need to be exposed from the DDEX provider (or maybe the ADO.NET data provider) in order to make Visual Studio add those refresh statements to the update/insert commands? The MSDN documentation for the Advanced SQL Generation Options Dialog Box has a note stating, “Refreshing the data table is only supported on databases that support batching of SQL statements.” This seems to imply that a .NET data provider might need to expose some property indicating such behavior is supported. But I cannot find it. Any ideas?

    Read the article

  • why DataColumn AllowDbNull is true even if oracle db does not allow null

    - by matti
    Hi. I have column SomeId in table SomeLink. When I look with tOra or Sql Plus Worksheet both state: tOra: Column name Data type Default Null Comment SOMEID INTEGER {null} NOT NULL {null} Sql Plus: SOMEID NOT NULL NUMBER(38) I have authored a method that's intended to give default values to all NOT NULL fields that don't have values: public static void GetDefaultValuesForNonNullColumns(DataRow row) { foreach(DataColumn col in row.Table.Columns) { if (Convert.IsDBNull(row[col]) && !col.AllowDBNull) { if (ColumnIsNumeric(col.DataType)) row[col] = 0; else if (col.DataType == typeof(DateTime)) row[col] = DateTime.Now; else if (col.DataType == typeof(String)) row[col] = string.Empty; else if (col.DataType == typeof(Char)) row[col] = ' '; else throw new Exception(string.Format("Unsupported column type: {0}", col.DataType)); } } } When SOMEID is handled in loop the AllowDBNull = true. I really can't understand. The table is created in DataSet like this: _someLinkAdptr = _dbFactory.CreateDataAdapter(); _someLinkAdptr.SelectCommand = _dbFactory.CreateCommand(); _someLinkAdptr.SelectCommand.Connection = _cnctn; _someLinkAdptr.SelectCommand.CommandText = GetSomeLinkSelectTxtAndParams(_someLinkAdptr.SelectCommand, UndefinedValue.ToString(), UndefinedValue.ToString()); Select command returns no rows. The idea is that I can then use commandbuilder to get InsertCommand without building it myself. The row is added to dataset's table like this: private static void CreateDocLink(int anId, int anotherId) { DataRow row = _someDataSet.Tables["SomeLink"].NewRow(); row["AnId"] = anId; row["AnotherId"] = anotherId; Utility.GetDefaultValuesForNonNullColumns(row); _someDataSet.Tables["SomeLink"].Rows.Add(row); } When DataAdapter is updated to oracle db I get: ORA-01400: cannot insert NULL into (SOMESCHEMA.SOMELINK.SOMEID) Cheers & BR -Matti

    Read the article

  • How can I synchronise two datatables and update the target in the database?

    - by Craig
    I am trying to synchronise two tables between two databases. I thought that the best way to do this would be to use the DataTable.Merge method. This seems to pick up the changes, but nothing ever gets committed to the database. So far I have: string tableName = "[Table_1]"; string sql = "select * from " + tableName; using (SqlConnection sourceConn = new SqlConnection(ConfigurationManager.ConnectionStrings["source"].ConnectionString)) { SqlDataAdapter sourceAdapter = new SqlDataAdapter(); sourceAdapter.SelectCommand = new SqlCommand(sql, sourceConn); sourceConn.Open(); DataSet sourceDs = new DataSet(); sourceAdapter.Fill(sourceDs); using (SqlConnection targetConn = new SqlConnection(ConfigurationManager.ConnectionStrings["target"].ConnectionString)) { SqlDataAdapter targetAdapter = new SqlDataAdapter(); targetAdapter.SelectCommand = new SqlCommand(sql, targetConn); SqlCommandBuilder builder = new SqlCommandBuilder(targetAdapter); targetAdapter.InsertCommand = builder.GetInsertCommand(); targetAdapter.UpdateCommand = builder.GetUpdateCommand(); targetAdapter.DeleteCommand = builder.GetDeleteCommand(); targetConn.Open(); DataSet targetDs = new DataSet(); targetAdapter.Fill(targetDs); targetDs.Tables[0].TableName = tableName; sourceDs.Tables[0].TableName = tableName; targetDs.Tables[0].Merge(sourceDs.Tables[0]); targetAdapter.Update(targetDs.Tables[0]); } } At the present time, there is one row in the source that is not in the target. This row is never transferred. I have also tried it with an empty target, and nothing is transferred.

    Read the article

  • ASP.NET SqlDataSource update and create FK reference

    - by William
    The short version: I have a grid view bound to a data source which has a SelectCommand with a left join in it because the FK can be null. On Update I want to create a record in the FK table if the FK is null and then update the parent table with the new records ID. Is this possible to do with just SqlDataSources? The detailed version: I have two tables: Company and Address. The column Company.AddressId can be null. On my ascx page I am using a SqlDataSource to select a left join of company and address and a GridView to display the results. By having my UpdateCommand and DeleteCommand of the SqlDataSource execute two statements separated by a semi-colon I am able to use the GridView's Edit and Delete functionality to update both table simultaneously. The problem I have is when the Company.AddressId is null. What I need to have happen is have the data source create a record in the Address table and then update the Company table with the new Address.ID then proceed with the update as usual. I would like to do this with just data sources if possible for consistency/simplicity sake. Is it possible to have my data source do this, or perhaps add a second data source to the page to handle some of this? Once I have that working I can probably figure out how to make it work with the InsertCommand as well but if you are on a roll and have an answer for how to make that fly as well feel free to provide it. Thanks.

    Read the article

  • Insert Stored Procedure does not Create Database Record

    - by SidC
    Hello All, I have the following stored procedure: ALTER PROCEDURE Pro_members_Insert @id int outPut, @LoginName nvarchar(50), @Password nvarchar(15), @FirstName nvarchar(100), @LastName nvarchar(100), @signupDate smalldatetime, @Company nvarchar(100), @Phone nvarchar(50), @Email nvarchar(150), @Address nvarchar(255), @PostalCode nvarchar(10), @State_Province nvarchar(100), @City nvarchar(50), @countryCode nvarchar(4), @active bit, @activationCode nvarchar(50) AS declare @usName as varchar(50) set @usName='' select @usName=isnull(LoginName,'') from members where LoginName=@LoginName if @usName <> '' begin set @ID=-3 RAISERROR('User Already exist.', 16, 1) return end set @usName='' select @usName=isnull(email,'') from members where Email=@Email if @usName <> '' begin set @ID=-4 RAISERROR('Email Already exist.', 16, 1) return end declare @MemID as int select @memID=isnull(max(ID),0)+1 from members INSERT INTO members ( id, LoginName, Password, FirstName, LastName, signupDate, Company, Phone, Email, Address, PostalCode, State_Province, City, countryCode, active,activationCode) VALUES ( @Memid, @LoginName, @Password, @FirstName, @LastName, @signupDate, @Company, @Phone, @Email, @Address, @PostalCode, @State_Province, @City, @countryCode, @active,@activationCode) if @@error <> 0 set @ID=-1 else set @id=@memID Note that I've "inherited" this sproc and the database. I am trying to insert a new record from my signup.aspx page. My SQLDataSource is as follows: <asp:SqlDataSource runat="server" ID="dsAddMember" ConnectionString="rmsdbuser" InsertCommandType="StoredProcedure" InsertCommand="Pro_members_Insert" ProviderName="System.Data.SqlClient"> The click handler for btnSave is as follows: Protected Sub btnSave_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnSave.Click Try dsAddMember.DataBind() Catch ex As Exception End Try End Sub When I run this page, signup.aspx, provide required fields and click submit, the page simply reloads and the database table does not reflect the newly-inserted record. Questions: 1. How do I catch the error messages that might be returned from the sproc? 2. Please advise how to change signup.aspx so that the insert occurs. Thanks, Sid

    Read the article

  • How to configure C# Typed Datasets when calling OracleDataAdapter.Update() on Oracle Stored Procedur

    - by John_D
    I am writing a C# Windows Forms application which calls Oracle stored procedures. I chose to use typed datasets in the application, these correctly populate various datagrids, but I am having trouble when invoking the UpdateCommand or the InsertCommand. I have manually coded these commands because a) I am using Oracle stored procedures and b) I don't trust CommandBuilder ;) I am using VS2008 and Oracle 9i I don't have trouble executing stored procedures in SQL Server or Oracle when simply calling them from the .ExecuteNonQuery command; neither do I have problems executing SQL statements directly and updating the database. The problems only arise when executing the changed rows with OracleDataAdapter.Update(). I am specifying the correct set of rows (added, changed etc.) The main error I am getting (after a lot of experimentation with increasingly simpler SPs finishing with just one int parameter) is "PLS-00306: wrong number or type of arguments in call to 'PROCNAME'" I have tried prefixing the Oracle parameter both with ':' and without. Suffice to say I am losing the will to live. Has anyone any more ideas I could try next? Thanks

    Read the article

  • Bulk inserting best way to about it? + Helping me understand fully what I found so far

    - by chobo2
    Hi So I saw this post here and read it and it seems like bulk copy might be the way to go. http://stackoverflow.com/questions/682015/whats-the-best-way-to-bulk-database-inserts-from-c I still have some questions and want to know how things actually work. So I found 2 tutorials. http://www.codeproject.com/KB/cs/MultipleInsertsIn1dbTrip.aspx#_Toc196622241 http://www.codeproject.com/KB/linq/BulkOperations_LinqToSQL.aspx First way uses 2 ado.net 2.0 features. BulkInsert and BulkCopy. the second one uses linq to sql and OpenXML. This sort of appeals to me as I am using linq to sql already and prefer it over ado.net. However as one person pointed out in the posts what he just going around the issue at the cost of performance( nothing wrong with that in my opinion) First I will talk about the 2 ways in the first tutorial I am using VS2010 Express, .net 4.0, MVC 2.0, SQl Server 2005 Is ado.net 2.0 the most current version? Based on the technology I am using, is there some updates to what I am going to show that would improve it somehow? Is there any thing that these tutorial left out that I should know about? BulkInsert I am using this table for all the examples. CREATE TABLE [dbo].[TBL_TEST_TEST] ( ID INT IDENTITY(1,1) PRIMARY KEY, [NAME] [varchar](50) ) SP Code USE [Test] GO /****** Object: StoredProcedure [dbo].[sp_BatchInsert] Script Date: 05/19/2010 15:12:47 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO ALTER PROCEDURE [dbo].[sp_BatchInsert] (@Name VARCHAR(50) ) AS BEGIN INSERT INTO TBL_TEST_TEST VALUES (@Name); END C# Code /// <summary> /// Another ado.net 2.0 way that uses a stored procedure to do a bulk insert. /// Seems slower then "BatchBulkCopy" way and it crashes when you try to insert 500,000 records in one go. /// http://www.codeproject.com/KB/cs/MultipleInsertsIn1dbTrip.aspx#_Toc196622241 /// </summary> private static void BatchInsert() { // Get the DataTable with Rows State as RowState.Added DataTable dtInsertRows = GetDataTable(); SqlConnection connection = new SqlConnection(connectionString); SqlCommand command = new SqlCommand("sp_BatchInsert", connection); command.CommandType = CommandType.StoredProcedure; command.UpdatedRowSource = UpdateRowSource.None; // Set the Parameter with appropriate Source Column Name command.Parameters.Add("@Name", SqlDbType.VarChar, 50, dtInsertRows.Columns[0].ColumnName); SqlDataAdapter adpt = new SqlDataAdapter(); adpt.InsertCommand = command; // Specify the number of records to be Inserted/Updated in one go. Default is 1. adpt.UpdateBatchSize = 1000; connection.Open(); int recordsInserted = adpt.Update(dtInsertRows); connection.Close(); } So first thing is the batch size. Why would you set a batch size to anything but the number of records you are sending? Like I am sending 500,000 records so I did a Batch size of 500,000. Next why does it crash when I do this? If I set it to 1000 for batch size it works just fine. System.Data.SqlClient.SqlException was unhandled Message="A transport-level error has occurred when sending the request to the server. (provider: Shared Memory Provider, error: 0 - No process is on the other end of the pipe.)" Source=".Net SqlClient Data Provider" ErrorCode=-2146232060 Class=20 LineNumber=0 Number=233 Server="" State=0 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 TestIQueryable.Program.BatchInsert() in C:\Users\a\Downloads\TestIQueryable\TestIQueryable\TestIQueryable\Program.cs:line 124 at TestIQueryable.Program.Main(String[] args) in C:\Users\a\Downloads\TestIQueryable\TestIQueryable\TestIQueryable\Program.cs:line 16 InnerException: Time it took to insert 500,000 records with insert batch size of 1000 took "2 mins and 54 seconds" Of course this is no official time I sat there with a stop watch( I am sure there are better ways but was too lazy to look what they where) So I find that kinda slow compared to all my other ones(expect the linq to sql insert one) and I am not really sure why. Next I looked at bulkcopy /// <summary> /// An ado.net 2.0 way to mass insert records. This seems to be the fastest. /// http://www.codeproject.com/KB/cs/MultipleInsertsIn1dbTrip.aspx#_Toc196622241 /// </summary> private static void BatchBulkCopy() { // Get the DataTable DataTable dtInsertRows = GetDataTable(); using (SqlBulkCopy sbc = new SqlBulkCopy(connectionString, SqlBulkCopyOptions.KeepIdentity)) { sbc.DestinationTableName = "TBL_TEST_TEST"; // Number of records to be processed in one go sbc.BatchSize = 500000; // Map the Source Column from DataTabel to the Destination Columns in SQL Server 2005 Person Table // sbc.ColumnMappings.Add("ID", "ID"); sbc.ColumnMappings.Add("NAME", "NAME"); // Number of records after which client has to be notified about its status sbc.NotifyAfter = dtInsertRows.Rows.Count; // Event that gets fired when NotifyAfter number of records are processed. sbc.SqlRowsCopied += new SqlRowsCopiedEventHandler(sbc_SqlRowsCopied); // Finally write to server sbc.WriteToServer(dtInsertRows); sbc.Close(); } } This one seemed to go really fast and did not even need a SP( can you use SP with bulk copy? If you can would it be better?) BatchCopy had no problem with a 500,000 batch size.So again why make it smaller then the number of records you want to send? I found that with BatchCopy and 500,000 batch size it took only 5 seconds to complete. I then tried with a batch size of 1,000 and it only took 8 seconds. So much faster then the bulkinsert one above. Now I tried the other tutorial. USE [Test] GO /****** Object: StoredProcedure [dbo].[spTEST_InsertXMLTEST_TEST] Script Date: 05/19/2010 15:39:03 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO ALTER PROCEDURE [dbo].[spTEST_InsertXMLTEST_TEST](@UpdatedProdData nText) AS DECLARE @hDoc int exec sp_xml_preparedocument @hDoc OUTPUT,@UpdatedProdData INSERT INTO TBL_TEST_TEST(NAME) SELECT XMLProdTable.NAME FROM OPENXML(@hDoc, 'ArrayOfTBL_TEST_TEST/TBL_TEST_TEST', 2) WITH ( ID Int, NAME varchar(100) ) XMLProdTable EXEC sp_xml_removedocument @hDoc C# code. /// <summary> /// This is using linq to sql to make the table objects. /// It is then serailzed to to an xml document and sent to a stored proedure /// that then does a bulk insert(I think with OpenXML) /// http://www.codeproject.com/KB/linq/BulkOperations_LinqToSQL.aspx /// </summary> private static void LinqInsertXMLBatch() { using (TestDataContext db = new TestDataContext()) { TBL_TEST_TEST[] testRecords = new TBL_TEST_TEST[500000]; for (int count = 0; count < 500000; count++) { TBL_TEST_TEST testRecord = new TBL_TEST_TEST(); testRecord.NAME = "Name : " + count; testRecords[count] = testRecord; } StringBuilder sBuilder = new StringBuilder(); System.IO.StringWriter sWriter = new System.IO.StringWriter(sBuilder); XmlSerializer serializer = new XmlSerializer(typeof(TBL_TEST_TEST[])); serializer.Serialize(sWriter, testRecords); db.insertTestData(sBuilder.ToString()); } } So I like this because I get to use objects even though it is kinda redundant. I don't get how the SP works. Like I don't get the whole thing. I don't know if OPENXML has some batch insert under the hood but I do not even know how to take this example SP and change it to fit my tables since like I said I don't know what is going on. I also don't know what would happen if the object you have more tables in it. Like say I have a ProductName table what has a relationship to a Product table or something like that. In linq to sql you could get the product name object and make changes to the Product table in that same object. So I am not sure how to take that into account. I am not sure if I would have to do separate inserts or what. The time was pretty good for 500,000 records it took 52 seconds The last way of course was just using linq to do it all and it was pretty bad. /// <summary> /// This is using linq to sql to to insert lots of records. /// This way is slow as it uses no mass insert. /// Only tried to insert 50,000 records as I did not want to sit around till it did 500,000 records. /// http://www.codeproject.com/KB/linq/BulkOperations_LinqToSQL.aspx /// </summary> private static void LinqInsertAll() { using (TestDataContext db = new TestDataContext()) { db.CommandTimeout = 600; for (int count = 0; count < 50000; count++) { TBL_TEST_TEST testRecord = new TBL_TEST_TEST(); testRecord.NAME = "Name : " + count; db.TBL_TEST_TESTs.InsertOnSubmit(testRecord); } db.SubmitChanges(); } } I did only 50,000 records and that took over a minute to do. So I really narrowed it done to the linq to sql bulk insert way or bulk copy. I am just not sure how to do it when you have relationship for either way. I am not sure how they both stand up when doing updates instead of inserts as I have not gotten around to try it yet. I don't think I will ever need to insert/update more than 50,000 records at one type but at the same time I know I will have to do validation on records before inserting so that will slow it down and that sort of makes linq to sql nicer as your got objects especially if your first parsing data from a xml file before you insert into the database. Full C# code using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Xml.Serialization; using System.Data; using System.Data.SqlClient; namespace TestIQueryable { class Program { private static string connectionString = ""; static void Main(string[] args) { BatchInsert(); Console.WriteLine("done"); } /// <summary> /// This is using linq to sql to to insert lots of records. /// This way is slow as it uses no mass insert. /// Only tried to insert 50,000 records as I did not want to sit around till it did 500,000 records. /// http://www.codeproject.com/KB/linq/BulkOperations_LinqToSQL.aspx /// </summary> private static void LinqInsertAll() { using (TestDataContext db = new TestDataContext()) { db.CommandTimeout = 600; for (int count = 0; count < 50000; count++) { TBL_TEST_TEST testRecord = new TBL_TEST_TEST(); testRecord.NAME = "Name : " + count; db.TBL_TEST_TESTs.InsertOnSubmit(testRecord); } db.SubmitChanges(); } } /// <summary> /// This is using linq to sql to make the table objects. /// It is then serailzed to to an xml document and sent to a stored proedure /// that then does a bulk insert(I think with OpenXML) /// http://www.codeproject.com/KB/linq/BulkOperations_LinqToSQL.aspx /// </summary> private static void LinqInsertXMLBatch() { using (TestDataContext db = new TestDataContext()) { TBL_TEST_TEST[] testRecords = new TBL_TEST_TEST[500000]; for (int count = 0; count < 500000; count++) { TBL_TEST_TEST testRecord = new TBL_TEST_TEST(); testRecord.NAME = "Name : " + count; testRecords[count] = testRecord; } StringBuilder sBuilder = new StringBuilder(); System.IO.StringWriter sWriter = new System.IO.StringWriter(sBuilder); XmlSerializer serializer = new XmlSerializer(typeof(TBL_TEST_TEST[])); serializer.Serialize(sWriter, testRecords); db.insertTestData(sBuilder.ToString()); } } /// <summary> /// An ado.net 2.0 way to mass insert records. This seems to be the fastest. /// http://www.codeproject.com/KB/cs/MultipleInsertsIn1dbTrip.aspx#_Toc196622241 /// </summary> private static void BatchBulkCopy() { // Get the DataTable DataTable dtInsertRows = GetDataTable(); using (SqlBulkCopy sbc = new SqlBulkCopy(connectionString, SqlBulkCopyOptions.KeepIdentity)) { sbc.DestinationTableName = "TBL_TEST_TEST"; // Number of records to be processed in one go sbc.BatchSize = 500000; // Map the Source Column from DataTabel to the Destination Columns in SQL Server 2005 Person Table // sbc.ColumnMappings.Add("ID", "ID"); sbc.ColumnMappings.Add("NAME", "NAME"); // Number of records after which client has to be notified about its status sbc.NotifyAfter = dtInsertRows.Rows.Count; // Event that gets fired when NotifyAfter number of records are processed. sbc.SqlRowsCopied += new SqlRowsCopiedEventHandler(sbc_SqlRowsCopied); // Finally write to server sbc.WriteToServer(dtInsertRows); sbc.Close(); } } /// <summary> /// Another ado.net 2.0 way that uses a stored procedure to do a bulk insert. /// Seems slower then "BatchBulkCopy" way and it crashes when you try to insert 500,000 records in one go. /// http://www.codeproject.com/KB/cs/MultipleInsertsIn1dbTrip.aspx#_Toc196622241 /// </summary> private static void BatchInsert() { // Get the DataTable with Rows State as RowState.Added DataTable dtInsertRows = GetDataTable(); SqlConnection connection = new SqlConnection(connectionString); SqlCommand command = new SqlCommand("sp_BatchInsert", connection); command.CommandType = CommandType.StoredProcedure; command.UpdatedRowSource = UpdateRowSource.None; // Set the Parameter with appropriate Source Column Name command.Parameters.Add("@Name", SqlDbType.VarChar, 50, dtInsertRows.Columns[0].ColumnName); SqlDataAdapter adpt = new SqlDataAdapter(); adpt.InsertCommand = command; // Specify the number of records to be Inserted/Updated in one go. Default is 1. adpt.UpdateBatchSize = 500000; connection.Open(); int recordsInserted = adpt.Update(dtInsertRows); connection.Close(); } private static DataTable GetDataTable() { // You First need a DataTable and have all the insert values in it DataTable dtInsertRows = new DataTable(); dtInsertRows.Columns.Add("NAME"); for (int i = 0; i < 500000; i++) { DataRow drInsertRow = dtInsertRows.NewRow(); string name = "Name : " + i; drInsertRow["NAME"] = name; dtInsertRows.Rows.Add(drInsertRow); } return dtInsertRows; } static void sbc_SqlRowsCopied(object sender, SqlRowsCopiedEventArgs e) { Console.WriteLine("Number of records affected : " + e.RowsCopied.ToString()); } } }

    Read the article

  • can we use both custom button and inbuilt button in datagridview

    - by Srikanth Mattihalli
    HI all, I am using Datagridview in asp.net. I have used custom buttons of up and down in the datagridview along with edit,delete and paging options. I am handling the up down buttons by raising events in rowcommand and the code is as below string command = e.CommandName; Response.Write(e.CommandArgument.ToString()); int index = Convert.ToInt32(e.CommandArgument.ToString()); int count = GridView1.Rows.Count; int keyValue = Convert.ToInt32(GridView1.Rows[index].Cells1.Text); string value = GridView1.Rows[index].Cells[4].Text; SqlConnection conn = new SqlConnection(SqlDataSource1.ConnectionString); SqlCommand cmd = new SqlCommand(); if (command == "up") { if (index > 0) { index = index - 1; int keyValue1 = Convert.ToInt32(GridView1.Rows[index].Cells[1].Text); string value1 = GridView1.Rows[index].Cells[4].Text; cmd.Connection = conn; cmd.CommandText = "UPDATE [category] SET [order_id] = '" + value + "' WHERE [category_id]=" + keyValue1 + ";UPDATE [category] SET [order_id] = '" + value1 + "' WHERE [category_id]=" + keyValue + ";"; conn.Open(); cmd.ExecuteNonQuery(); conn.Close(); } } else if (command == "down") { if (index < count - 1) { index = index + 1; int keyValue1 = Convert.ToInt32(GridView1.Rows[index].Cells[1].Text); string value1 = GridView1.Rows[index].Cells[4].Text; cmd.Connection = conn; cmd.CommandText = "UPDATE [category] SET [order_id] = '" + value + "' WHERE [category_id]=" + keyValue1 + ";UPDATE [category] SET [order_id] = '" + value1 + "' WHERE [category_id]=" + keyValue + ";"; conn.Open(); cmd.ExecuteNonQuery(); conn.Close(); } } Response.Redirect("Default.aspx"); Designer file " DeleteCommand="DELETE FROM [category] WHERE [category_id] = @category_id" InsertCommand="INSERT INTO [category] ([categoryname], [navigation_url], [order_id]) VALUES (@categoryname, @navigation_url, @order_id)" SelectCommand="SELECT * FROM [category] order by order_id" UpdateCommand="UPDATE [category] SET [categoryname] = @categoryname, [navigation_url] = @navigation_url, [order_id] = @order_id WHERE [category_id] = @category_id" After this my edit,delete and paging is not working bcoz of event conflicts. Can anyone plz help me on this, so that i will be able to use both custom buttons(up and down) and edit,delete and paging features.

    Read the article

  • Selecting one row when working with typed datasets.

    - by Wodzu
    I have a typed dataset in my project. I would like to populate a datatable with only one row instead of all rows. The selected row must be based on the primary key column. I know I could modify the designer code to achive this functionality however if I change the code in the designer I risk that this code will be deleted when I update my datased via designer in the future. So I wanted to alter the SelectCommand not in the designer but just before firing up MyTypedTableAdapter.Fill method. The strange thing is that the designer does not create a SelectCommand! It creates all other commands but not this one. If it would create SelectCommand I could alter it in this way: this.operatorzyTableAdapter.Adapter.SelectCommand.CommandText += " WHERE MyColumn = 1"; It is far from perfection but atleast I would not have to modify the designer's work. unfortunately as I said earlier the SelectCommand is not created. Instead designer creates something like this: [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] private void InitCommandCollection() { this._commandCollection = new global::System.Data.SqlClient.SqlCommand[1]; this._commandCollection[0] = new global::System.Data.SqlClient.SqlCommand(); this._commandCollection[0].Connection = this.Connection; this._commandCollection[0].CommandText = "SELECT Ope_OpeID, Ope_Kod, Ope_Haslo, Ope_Imie, Ope_Nazwisko FROM dbo.Operatorzy"; this._commandCollection[0].CommandType = global::System.Data.CommandType.Text; } It doesn't make sense in my opinion. Why to create UpdateCommand, InsertCommand and DeleteCommand but do not create SelectCommand? I could bear with this but this._commandCollection is private so I cannot acces it outside of the class code. I don't know how to get into this collection without changing the designer's code. The idea which I have is to expose the collection via partial class definition. However I want to introduce many typed datasets and I really don't want to create partial class definition for each of them. Please note that I am using .NET 3.5. I've found this article about accessing private properties but it concerns .NET 4.0 Thanks for your time.

    Read the article

  • Own DataFormWebPart: Unable to display this Web Part.

    - by user307852
    Hi, What I want is to display a paginable list from my custom data source. All came from the fact that I needed some logical relationships between seach scopes and some dates. I considered ContentQueryWebpart, but CAML is too complicated as I have plenty of different conditions, CoreResults webpart is too limited as it uses KeyWordQuery so I inherited from DataFormWebPart to display my own custom search results from my own custom xml source. Thats the best way i am aware of... I knew I needed some configuration to write in my pageLayout like MyWebParts:MyCustomWebPart etc so I went to Designer, put DataFormWebPart on a page, linked it to list of pages, and set multiple item view and that gave me some configuration.. Firstly i checked if DataFormWebPart works when put on pageLayout and it sucessfully displayed my pages list in pages library. But that was not what I wanted, i needed to set my own XML data source... I then changed the configuration of WebPartPages:DataFormWebPart to match mine and detach from any listName or listId and I change the XSL tag to much simplier to display all results and now I am getting: Unable to display this Web Part. To troubleshoot the problem, open this Web page in a Microsoft SharePoint Foundation-compatible HTML editor such as Microsoft SharePoint Designer. If the problem persists, contact your Web server administrator. and there is no way to know what is wrong:/ The webpart public class MyCustomWebPart : DataFormWebPart{ public override void DataBind() { ...... XmlDataSource source = new XmlDataSource(); source.Data = doc.InnerXml; this.DataSource=source; base.DataBind(); } } The doc XML: <dsQueryResponse><Rows><Row URL="http://myserver/sites/sc/myDoc.doc" TITLE="Specification.doc" AUTHOR="System.String[]" /></Rows></dsQueryResponse> The webpart is in PageLayout, inserted without webpartzone: <MyWebParts:MyCustomWebPart runat="server" Description="" ListDisplayName="" PartOrder="2" HelpLink="" AllowRemove="True" IsVisible="True" AllowHide="True" UseSQLDataSourcePaging="True" ExportControlledProperties="True" DataSourceID="" Title="" ViewFlag="0" NoDefaultStyle="TRUE" AllowConnect="True" FrameState="Normal" PageSize="10" PartImageLarge="" AsyncRefresh="True" ExportMode="All" Dir="Default" DetailLink="" ShowWithSampleData="False" FrameType="None" PartImageSmall="" IsIncluded="True" SuppressWebPartChrome="False" AllowEdit="True" ManualRefresh="False" ChromeType="None" AutoRefresh="False" AutoRefreshInterval="60" AllowMinimize="True" ViewContentTypeId="" InitialAsyncDataFetch="False" MissingAssembly="Cannot import this Web Part." HelpMode="Modeless" ListUrl="" ID="g_c2180fb9_c667_42f3_aab3_c3340cb0ac5a" ConnectionID="00000000-0000-0000-0000-000000000000" AllowZoneChange="True" IsIncludedFilter="" __MarkupType="vsattributemarkup" __WebPartId="{C2233FB9-C667-42F3-AAB3-C334223C5A}" __AllowXSLTEditing="true" WebPart="true" Height="" Width=""> <Xsl> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/> <xsl:template match="/"> <xmp> <xsl:copy-of select="*"/> </xmp> </xsl:template> </xsl:stylesheet> </Xsl> <DataSources> <SharePoint:SPDataSource runat="server" DataSourceMode="List" SelectCommand="<View></View>" UpdateCommand="" InsertCommand="" DeleteCommand="" UseInternalName="True" ID="spdatasource3"> <SelectParameters> <asp:Parameter DefaultValue="0" Name="StartRowIndex"></asp:Parameter><asp:Parameter DefaultValue="0" Name="nextpagedata"> </asp:Parameter><asp:Parameter DefaultValue="10" Name="MaximumRows"></asp:Parameter> </SelectParameters> </SharePoint:SPDataSource> </DataSources> </MyWebParts:MyCustomWebPart>

    Read the article

  • ASP.Net: Insert null DateTime

    - by Vinzcent
    Hey I'am using a SQLDatasource in combination with a Formview. When I want to insert or update a DateTime that has no value, I always get an error. How do you insert a DateTime null. My SQLDataSource <asp:SqlDataSource ID="sqldsDetailOrder" runat="server" ConnectionString="<%$ ConnectionStrings:csBookStore %>" SelectCommand="SELECT 'AUTHOR' = tblAuthors.FIRSTNAME + ' ' + tblAuthors.LASTNAME, tblBooks.*, tblGenres.*, tblLanguages.*, tblOrders.* FROM tblAuthors INNER JOIN tblBooks ON tblAuthors.AUTHOR_ID = tblBooks.AUTHOR_ID INNER JOIN tblGenres ON tblBooks.GENRE_ID = tblGenres.GENRE_ID INNER JOIN tblLanguages ON tblBooks.LANG_ID = tblLanguages.LANG_ID INNER JOIN tblOrders ON tblBooks.BOOK_ID = tblOrders.BOOK_ID WHERE tblOrders.ID = @ID" DeleteCommand="DELETE FROM [tblOrders] WHERE [ID] = @ID" InsertCommand="INSERT INTO [tblOrders] ([NAME], [ADDRESS], [CITY], [PC], [DATE], [BOOK_ID], [COUNT], [AMOUNT], [DELIVERED], [DDATE], [PAID], [PDATE]) VALUES (@NAME, @ADDRESS, @CITY, @PC, @DATE, @BOOK_ID, @COUNT, @AMOUNT, @DELIVERED, @DDATE, @PAID, @PDATE)" UpdateCommand="UPDATE [tblOrders] SET [NAME] = @NAME, [ADDRESS] = @ADDRESS, [CITY] = @CITY, [PC] = @PC, [DATE] = @DATE, [BOOK_ID] = @BOOK_ID, [COUNT] = @COUNT, [AMOUNT] = @AMOUNT, [DELIVERED] = @DELIVERED, [DDATE] = @DDATE, [PAID] = @PAID, [PDATE] = @PDATE WHERE [ID] = @ID"> <SelectParameters> <asp:ControlParameter ControlID="gvOrdersAdmin" Name="ID" PropertyName="SelectedValue" Type="Int32" /> </SelectParameters> <DeleteParameters> <asp:Parameter Name="ID" Type="Int32" /> </DeleteParameters> <UpdateParameters> <asp:Parameter Name="NAME" Type="String" /> <asp:Parameter Name="ADDRESS" Type="String" /> <asp:Parameter Name="CITY" Type="String" /> <asp:Parameter Name="PC" Type="String" /> <asp:Parameter DbType="DateTime" Name="DATE" /> <asp:Parameter Name="BOOK_ID" Type="Int32" /> <asp:Parameter Name="COUNT" Type="Int32" /> <asp:Parameter Name="AMOUNT" Type="Decimal" /> <asp:Parameter Name="DELIVERED" Type="Boolean" /> <asp:Parameter DbType="DateTime" Name="DDATE" /> <asp:Parameter Name="PAID" Type="Boolean" /> <asp:Parameter DbType="DateTime" Name="PDATE" /> <asp:Parameter Name="ID" Type="Int32" /> </UpdateParameters> <InsertParameters> <asp:Parameter Name="NAME" Type="String" /> <asp:Parameter Name="ADDRESS" Type="String" /> <asp:Parameter Name="CITY" Type="String" /> <asp:Parameter Name="PC" Type="String" /> <asp:Parameter DbType="DateTime" Name="DATE" /> <asp:Parameter Name="BOOK_ID" Type="Int32" /> <asp:Parameter Name="COUNT" Type="Int32" /> <asp:Parameter Name="AMOUNT" Type="Decimal" /> <asp:Parameter Name="DELIVERED" Type="Boolean" /> <asp:Parameter DbType="DateTime?" Name="DDATE" /> <asp:Parameter Name="PAID" Type="Boolean" /> <asp:Parameter DbType="DateTime" Name="PDATE" /> </InsertParameters> </asp:SqlDataSource> Thanks Vincent

    Read the article

  • Gridview delete/edit not working when using select parameter

    - by Brian Carroll
    new to ASP.NET. I created a sqldatasource and set up basic select query (SELECT * FROM Accounts) using the wizard. I then had the sqldatasource wizard create the INSERT, EDIT and DELETE queries. Connected this datasource to a gridview with EDITING and DELETING enabled. Everything works fine. The SELECT query returns all records and I can edit/delete them. Now I need to send a parameter to the SELECT command to filter the records to those with the user's id (pulled from Membership.GetUser). When I add this parameter, the SELECT command works fine, but the EDIT/DELETE buttons in the gridview no longer work. No error is generated. The page refreshes but the records were not updated in the database. I don't understand what is wrong. CODE: <% Dim u As MembershipUser Dim userid As String u = Membership.GetUser(User.Identity.Name) userid = u.ProviderUserKey.ToString SqlDataSource1.SelectParameters("UserId").DefaultValue = userid %> <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="ID" DataSourceID="SqlDataSource1"> <Columns> <asp:CommandField ShowDeleteButton="True" ShowEditButton="True" /> <asp:BoundField DataField="ID" HeaderText="ID" InsertVisible="False" ReadOnly="True" SortExpression="ID" /> <asp:BoundField DataField="UserId" HeaderText="UserId" SortExpression="UserId" /> <asp:BoundField DataField="AccountName" HeaderText="AccountName" SortExpression="AccountName" /> <asp:BoundField DataField="DateAdded" HeaderText="DateAdded" SortExpression="DateAdded" /> <asp:BoundField DataField="LastModified" HeaderText="LastModified" SortExpression="LastModified" /> </Columns> </asp:GridView> <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:CheckingConnectionString %>" DeleteCommand="DELETE FROM [Accounts] WHERE [ID] = @ID" InsertCommand="INSERT INTO [Accounts] ([UserId], [AccountName], [DateAdded], [LastModified]) VALUES (@UserId, @AccountName, @DateAdded, @LastModified)" SelectCommand="SELECT * FROM [Accounts] WHERE [UserId] = @UserId" UpdateCommand="UPDATE [Accounts] SET [UserId] = @UserId, [AccountName] = @AccountName, [DateAdded] = @DateAdded, [LastModified] = @LastModified WHERE [ID] = @ID"> <DeleteParameters> <asp:Parameter Name="ID" Type="Int32" /> </DeleteParameters> <InsertParameters> <asp:Parameter Name="UserId" Type="String" /> <asp:Parameter Name="AccountName" Type="String" /> <asp:Parameter Name="DateAdded" Type="DateTime" /> <asp:Parameter Name="LastModified" Type="DateTime" /> </InsertParameters> <UpdateParameters> <asp:Parameter Name="UserId" Type="String" /> <asp:Parameter Name="AccountName" Type="String" /> <asp:Parameter Name="DateAdded" Type="DateTime" /> <asp:Parameter Name="LastModified" Type="DateTime" /> <asp:Parameter Name="ID" Type="Int32" /> </UpdateParameters> <SelectParameters> <asp:Parameter Name="UserId"/> </SelectParameters> </asp:SqlDataSource>

    Read the article

  • ASP.NET how to save textbox in database?

    - by mahsoon
    I used some textboxes to get some info from users + a sqldatasource <tr> <td class="style3" colspan="3" style="font-size: medium; font-family: 'B Nazanin'; font-weight: bold; position: relative; right: 170px" > &nbsp; ????? ??????? ????</td> </tr> <tr> <td class="style3"> &nbsp;&nbsp;&nbsp; <asp:Label ID="Label1" runat="server" Text=" ???: " Font-Bold="True" Font-Names="B Nazanin" Font-Size="Medium"></asp:Label> </td> <td class="style2"> <asp:TextBox ID="FirstName" runat="server"></asp:TextBox> </td> <td class="style4"> <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" Display="Dynamic" ErrorMessage="???? ???? ??? ?????? ???" ControlToValidate="FirstName">*</asp:RequiredFieldValidator> </td> </tr> <tr> <td class="style3"> &nbsp;&nbsp;&nbsp;<asp:Label ID="Label2" runat="server" Text=" ??? ????????: " Font-Bold="True" Font-Names="B Nazanin" Font-Size="Medium"></asp:Label> </td> <td class="style2"> <asp:TextBox ID="LastName" runat="server"></asp:TextBox> </td> <td class="style4"> <asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" Display="Dynamic" ErrorMessage="???? ???? ??? ???????? ?????? ???" ControlToValidate="LastName">*</asp:RequiredFieldValidator> </td> </tr> <tr> <td class="style3"> &nbsp;&nbsp;&nbsp;<asp:Label ID="Label3" runat="server" Text=" ????? ???????? : " Font-Bold="True" Font-Names="B Nazanin" Font-Size="Medium"></asp:Label> </td> <td class="style2"> <asp:TextBox ID="StudentNumber" runat="server"></asp:TextBox> </td> <td class="style4"> <asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server" Display="Dynamic" ErrorMessage="???? ???? ????? ???????? ?????? ???" ControlToValidate="StudentNumber">*</asp:RequiredFieldValidator> </td> </tr> <tr> <td class="style3"> &nbsp;&nbsp;<asp:Label ID="Label4" runat="server" Text="  ????? ???? : " Font-Bold="True" Font-Names="B Nazanin" Font-Size="Medium"></asp:Label> </td> <td class="style2"> <asp:TextBox ID="DateOfBirth" runat="server"></asp:TextBox> </td> <td class="style4"> <asp:CompareValidator ID="CompareValidator1" runat="server" Display="Dynamic" ErrorMessage="????? ???? ?????? ?? ???? ??????" Operator="DataTypeCheck" Type="Date" ControlToValidate="dateOfBirth"></asp:CompareValidator> </td> </tr> <tr> <td class="style3"> &nbsp;</td> <td class="style2"> <asp:Button ID="SaveButton" runat="server" Text=" ????? ???????" Width="102px" style="margin-right: 15px; height: 26px;" /> </td> <td class="style4"> <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:ASPNETDBConnectionString1 %>" SelectCommand="SELECT aspnet_personalInformation.FirstName, aspnet_personalInformation.LastName, aspnet_personalInformation.StudentNumber, aspnet_personalInformation.DateOfBirth FROM aspnet_personalInformation INNER JOIN aspnet_Users ON aspnet_personalInformation.UserId = aspnet_Users.UserId WHERE aspnet_personalInformation.UserId=aspnet_Users.UserId ORDER BY aspnet_personalInformation.LastName" InsertCommand="INSERT INTO aspnet_PersonalInformation(UserId) SELECT UserId FROM aspnet_Profile"> </asp:SqlDataSource> </td> </tr> </table> i wanna save firstname lastname studentnumber and dateofbirth in aspnet_personalinformation table in database but before that, i fill one column of aspnet_personalinformation table named UserId by inserting sql command with aspnet_profile.userid now by running this code my table has still blankes protected void SaveButton_Click(object sender, EventArgs e) { string str= "Data Source=.\\SQLEXPRESS;AttachDbFilename=|DataDirectory|\\ASPNETDB.MDF;Integrated Security=True;User Instance=True"; SqlConnection con = new SqlConnection(str); con.Open(); string query = "INSERT INTO aspnet_PersonalInformation( FirstName, LastName,StudentNumber,DateOfBirth) VALUES ('" + this.FirstName.Text + "','" + this.LastName.Text + "','" + this.StudentNumber.Text + "','" + this.DateOfBirth.Text + "') where aspnet_PersonalInformation.UserId=aspnet_Profile.UserID"; SqlCommand cmd=new SqlCommand(query,con); cmd.ExecuteNonQuery(); con.Close(); } but it doesn't work help me plz

    Read the article

  • How do I insert data using a DetailsView into an access database without everything breaking?

    - by Steve
    Hey I'm getting the error: Data type mismatch in criteria expression. when I try to submit a DetailsView insert. Code for Default.aspx: (from inside an asp:Content tag) <asp:DetailsView ID="DetailsView1" runat="server" Height="50px" Width="125px" AutoGenerateRows="False" DataKeyNames="user_id" DataSourceID="AccessDataSource1" CellPadding="4" ForeColor="#333333" GridLines="None"> <FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" /> <CommandRowStyle BackColor="#E2DED6" Font-Bold="True" /> <RowStyle BackColor="#F7F6F3" ForeColor="#333333" /> <FieldHeaderStyle BackColor="#E9ECF1" Font-Bold="True" /> <PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" /> <Fields> <asp:BoundField DataField="email" HeaderText="email" SortExpression="email" /> <asp:BoundField DataField="password" HeaderText="password" SortExpression="password" /> <asp:BoundField DataField="users_name" HeaderText="users_name" SortExpression="users_name" /> <asp:BoundField DataField="image_path" HeaderText="image_path" SortExpression="image_path" /> <asp:BoundField DataField="mobile" HeaderText="mobile" SortExpression="mobile" /> <asp:BoundField DataField="twitter" HeaderText="twitter" SortExpression="twitter" /> <asp:TemplateField HeaderText="privacy_level_id" SortExpression="privacy_level_id"> <InsertItemTemplate> <asp:DropDownList ID="DropDownList2" runat="server" DataSourceID="AccessDataSource2" DataTextField="privacy_level_name" DataValueField="privacy_level_id"> </asp:DropDownList> <asp:AccessDataSource ID="AccessDataSource2" runat="server" DataFile="~/App_Data/VisageFinal.mdb" SelectCommand="SELECT * FROM [PrivacyLevels]"></asp:AccessDataSource> </InsertItemTemplate> <ItemTemplate> <asp:Label ID="Label1" runat="server" Text='<%# Bind("date_of_birth") %>'></asp:Label> </ItemTemplate> </asp:TemplateField> <asp:TemplateField HeaderText="course_id" SortExpression="course_id"> <EditItemTemplate> <asp:DropDownList ID="DropDownList3" runat="server" DataSourceID="AccessDataSource3" DataTextField="course_name" DataValueField="course_id"> </asp:DropDownList> <asp:AccessDataSource ID="AccessDataSource3" runat="server" DataFile="~/App_Data/VisageFinal.mdb" SelectCommand="SELECT * FROM [Courses]"> </asp:AccessDataSource> </EditItemTemplate> <InsertItemTemplate> <asp:DropDownList ID="DropDownList22" runat="server" DataSourceID="AccessDataSource22" DataTextField="privacy_level_name" DataValueField="privacy_level_id"> </asp:DropDownList> <asp:AccessDataSource ID="AccessDataSource22" runat="server" DataFile="~/App_Data/VisageFinal.mdb" SelectCommand="SELECT * FROM [PrivacyLevels]"></asp:AccessDataSource> </InsertItemTemplate> <ItemTemplate> <asp:DropDownList ID="DropDownList3" runat="server" DataSourceID="AccessDataSource3" DataTextField="course_name" DataValueField="course_id" Enabled="False"> </asp:DropDownList> <asp:AccessDataSource ID="AccessDataSource3" runat="server" DataFile="~/App_Data/VisageFinal.mdb" SelectCommand="SELECT * FROM [Courses]"></asp:AccessDataSource> </ItemTemplate> </asp:TemplateField> <asp:TemplateField HeaderText="nationality_id" SortExpression="nationality_id"> <EditItemTemplate> <asp:DropDownList ID="DropDownList1" runat="server" DataSourceID="AccessDataSource20" DataTextField="nationality_name" DataValueField="nationality_id"> </asp:DropDownList> <asp:AccessDataSource ID="AccessDataSource20" runat="server" DataFile="~/App_Data/VisageFinal.mdb" SelectCommand="SELECT * FROM [Nationalities]"> </asp:AccessDataSource> </EditItemTemplate> <InsertItemTemplate> <asp:DropDownList ID="DropDownList1" runat="server" DataSourceID="AccessDataSource20" DataTextField="nationality_name" DataValueField="nationality_id"> </asp:DropDownList> <asp:AccessDataSource ID="AccessDataSource20" runat="server" DataFile="~/App_Data/VisageFinal.mdb" SelectCommand="SELECT * FROM [Nationalities]"> </asp:AccessDataSource> </InsertItemTemplate> <ItemTemplate> <asp:DropDownList ID="DropDownList1" runat="server" DataSourceID="AccessDataSource20" DataTextField="nationality_name" DataValueField="nationality_id" Enabled="False"> </asp:DropDownList> <asp:AccessDataSource ID="AccessDataSource20" runat="server" DataFile="~/App_Data/VisageFinal.mdb" SelectCommand="SELECT * FROM [Nationalities]"> </asp:AccessDataSource> </ItemTemplate> </asp:TemplateField> <asp:TemplateField HeaderText="residence_id" SortExpression="residence_id"> <EditItemTemplate> <asp:DropDownList ID="DropDownList4" runat="server" DataSourceID="AccessDataSource4" DataTextField="residence_name" DataValueField="residence_id"> </asp:DropDownList> <asp:AccessDataSource ID="AccessDataSource4" runat="server" DataFile="~/App_Data/VisageFinal.mdb" SelectCommand="SELECT * FROM [Residences]"></asp:AccessDataSource> </EditItemTemplate> <InsertItemTemplate> <asp:DropDownList ID="DropDownList4" runat="server" DataSourceID="AccessDataSource4" DataTextField="residence_name" DataValueField="residence_id"> </asp:DropDownList> <asp:AccessDataSource ID="AccessDataSource4" runat="server" DataFile="~/App_Data/VisageFinal.mdb" SelectCommand="SELECT * FROM [Residences]"></asp:AccessDataSource> </InsertItemTemplate> <ItemTemplate> <asp:DropDownList ID="DropDownList4" runat="server" DataSourceID="AccessDataSource4" DataTextField="residence_name" DataValueField="residence_id" Enabled="False"> </asp:DropDownList> <asp:AccessDataSource ID="AccessDataSource4" runat="server" DataFile="~/App_Data/VisageFinal.mdb" SelectCommand="SELECT * FROM [Residences]"></asp:AccessDataSource> </ItemTemplate> </asp:TemplateField> <asp:BoundField DataField="course_year" HeaderText="course_year" SortExpression="course_year" /> <asp:TemplateField HeaderText="gender_id" SortExpression="gender_id"> <EditItemTemplate> <asp:DropDownList ID="DropDownList5" runat="server" DataSourceID="AccessDataSource5" DataTextField="gender_name" DataValueField="gender_id"> </asp:DropDownList> <asp:AccessDataSource ID="AccessDataSource5" runat="server" DataFile="~/App_Data/VisageFinal.mdb" SelectCommand="SELECT * FROM [Genders]"></asp:AccessDataSource> </EditItemTemplate> <InsertItemTemplate> <asp:DropDownList ID="DropDownList5" runat="server" DataSourceID="AccessDataSource5" DataTextField="gender_name" DataValueField="gender_id"> </asp:DropDownList> <asp:AccessDataSource ID="AccessDataSource5" runat="server" DataFile="~/App_Data/VisageFinal.mdb" SelectCommand="SELECT * FROM [Genders]"></asp:AccessDataSource> </InsertItemTemplate> <ItemTemplate> <asp:DropDownList ID="DropDownList5" runat="server" DataSourceID="AccessDataSource5" DataTextField="gender_name" DataValueField="gender_id" Enabled="False"> </asp:DropDownList> <asp:AccessDataSource ID="AccessDataSource5" runat="server" DataFile="~/App_Data/VisageFinal.mdb" SelectCommand="SELECT * FROM [Genders]"></asp:AccessDataSource> </ItemTemplate> </asp:TemplateField> <asp:CommandField ShowInsertButton="True" InsertText="Create my user!" /> </Fields> <HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" /> <EditRowStyle BackColor="#999999" /> <AlternatingRowStyle BackColor="White" ForeColor="#284775" /> </asp:DetailsView> <asp:Button ID="Button1" runat="server" Text="Button" /> <asp:AccessDataSource ID="AccessDataSource1" runat="server" DataFile="~/App_Data/VisageFinal.mdb" DeleteCommand="DELETE FROM [Users] WHERE [user_id] = ?" InsertCommand="INSERT INTO [Users] ([email], [password], [users_name], [image_path], [mobile], [twitter], [privacy_level_id], [nationality_id], [course_id], [residence_id], [course_year], [gender_id]) VALUES ('?', '?', '?', '?', '?', '?', ?, ?, ?, ?, ?, ?)" SelectCommand="SELECT * FROM [Users]" UpdateCommand="UPDATE [Users] SET [email] = ?, [password] = ?, [users_name] = ?, [date_of_birth] = ?, [image_path] = ?, [mobile] = ?, [twitter] = ?, [privacy_level_id] = ?, [nationality_id] = ?, [course_id] = ?, [residence_id] = ?, [has_set_privacy_level] = ?, [course_year] = ?, [gender_id] = ? WHERE [user_id] = ?"> <DeleteParameters> <asp:Parameter Name="user_id" Type="Int32" /> </DeleteParameters> <UpdateParameters> <asp:Parameter Name="email" Type="String" /> <asp:Parameter Name="password" Type="String" /> <asp:Parameter Name="users_name" Type="String" /> <asp:Parameter Name="image_path" Type="String" /> <asp:Parameter Name="mobile" Type="String" /> <asp:Parameter Name="twitter" Type="String" /> <asp:Parameter Name="privacy_level_id" Type="Int32" /> <asp:Parameter Name="nationality_id" Type="Int32" /> <asp:Parameter Name="course_id" Type="Int32" /> <asp:Parameter Name="residence_id" Type="Int32" /> <asp:Parameter Name="has_set_privacy_level" Type="Boolean" /> <asp:Parameter Name="course_year" Type="Int32" /> <asp:Parameter Name="gender_id" Type="Int32" /> <asp:Parameter Name="user_id" Type="Int32" /> </UpdateParameters> <InsertParameters> <asp:Parameter Name="email" Type="String" /> <asp:Parameter Name="password" Type="String" /> <asp:Parameter Name="users_name" Type="String" /> <asp:Parameter Name="image_path" Type="String" /> <asp:Parameter Name="mobile" Type="String" /> <asp:Parameter Name="twitter" Type="String" /> <asp:Parameter Name="privacy_level_id" Type="Int32" /> <asp:Parameter Name="nationality_id" Type="Int32" /> <asp:Parameter Name="course_id" Type="Int32" /> <asp:Parameter Name="residence_id" Type="Int32" /> <asp:Parameter Name="course_year" Type="Int32" /> <asp:Parameter Name="gender_id" Type="Int32" /> </InsertParameters> </asp:AccessDataSource> Any ideas what I've broken?

    Read the article

  • C#: No value given for one or more required parameter with FormView

    - by Vinzcent
    Hey, I am using a FormView and when I want to update something I have edited, I always get this error: No value given for one or more required parameters. I use a SQLDataSource in combination with a FormView This is the code of my SQLDataSource <asp:SqlDataSource ID="sqldsLokaalPrinters" runat="server" ConnectionString="<%$ ConnectionStrings:connRand2 %>" DeleteCommand="DELETE FROM [tblComputers] WHERE (([tblArtveldenr] = ?) OR ([tblArtveldenr] IS NULL AND ? IS NULL))" InsertCommand="INSERT INTO [tblComputers] ([tblArtveldenr], [tblNaam], [tblCLokaal_id], [tblPositie], [tblSerienr], [tblTCPIP], [tblFabrikant], [tblModel], [tblProcessor], [tblSnelheid], [tblKleur], [tblGeheugen], [tblHarddisk], [tblZip], [tblCD], [tblDVD], [tblNetwerk], [tblFirewire], [tblAanschafdatum], [tblCLeverabcierNr], [tblScherm], [tblLaptop]) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)" ProviderName="<%$ ConnectionStrings:connRand2.ProviderName %>" SelectCommand="SELECT * FROM [tblComputers] WHERE ([tblCLokaal_id] = ?)" UpdateCommand="UPDATE [tblComputers] SET [tblNaam] = ?, [tblCLokaal_id] = ?, [tblPositie] = ?, [tblSerienr] = ?, [tblTCPIP] = ?, [tblFabrikant] = ?, [tblModel] = ?, [tblProcessor] = ?, [tblSnelheid] = ?, [tblKleur] = ?, [tblGeheugen] = ?, [tblHarddisk] = ?, [tblZip] = ?, [tblCD] = ?, [tblDVD] = ?, [tblNetwerk] = ?, [tblFirewire] = ?, [tblAanschafdatum] = ?, [tblCLeverabcierNr] = ?, [tblScherm] = ?, [tblLaptop] = ? WHERE (([tblArtveldenr] = ?) OR ([tblArtveldenr] IS NULL AND ? IS NULL))"> <SelectParameters> <asp:SessionParameter Name="tblCLokaal_id" SessionField="lokaalID" Type="Int16" /> </SelectParameters> <DeleteParameters> <asp:Parameter Name="tblArtveldenr" Type="String" /> </DeleteParameters> <UpdateParameters> <asp:Parameter Name="tblNaam" Type="String" /> <asp:Parameter Name="tblCLokaal_id" Type="Int16" /> <asp:Parameter Name="tblPositie" Type="Int32" /> <asp:Parameter Name="tblSerienr" Type="String" /> <asp:Parameter Name="tblTCPIP" Type="String" /> <asp:Parameter Name="tblFabrikant" Type="String" /> <asp:Parameter Name="tblModel" Type="String" /> <asp:Parameter Name="tblProcessor" Type="String" /> <asp:Parameter Name="tblSnelheid" Type="Int32" /> <asp:Parameter Name="tblKleur" Type="String" /> <asp:Parameter Name="tblGeheugen" Type="Int32" /> <asp:Parameter Name="tblHarddisk" Type="Double" /> <asp:Parameter Name="tblZip" Type="String" /> <asp:Parameter Name="tblCD" Type="String" /> <asp:Parameter Name="tblDVD" Type="String" /> <asp:Parameter Name="tblNetwerk" Type="String" /> <asp:Parameter Name="tblFirewire" Type="Int32" /> <asp:Parameter Name="tblAanschafdatum" Type="DateTime" /> <asp:Parameter Name="tblCLeverabcierNr" Type="Int32" /> <asp:Parameter Name="tblScherm" Type="String" /> <asp:Parameter Name="tblLaptop" Type="Boolean" /> <asp:Parameter Name="tblArtveldenr" Type="String" /> </UpdateParameters> <InsertParameters> <asp:Parameter Name="tblArtveldenr" Type="String" /> <asp:Parameter Name="tblNaam" Type="String" /> <asp:Parameter Name="tblCLokaal_id" Type="Int16" /> <asp:Parameter Name="tblPositie" Type="Int32" /> <asp:Parameter Name="tblSerienr" Type="String" /> <asp:Parameter Name="tblTCPIP" Type="String" /> <asp:Parameter Name="tblFabrikant" Type="String" /> <asp:Parameter Name="tblModel" Type="String" /> <asp:Parameter Name="tblProcessor" Type="String" /> <asp:Parameter Name="tblSnelheid" Type="Int32" /> <asp:Parameter Name="tblKleur" Type="String" /> <asp:Parameter Name="tblGeheugen" Type="Int32" /> <asp:Parameter Name="tblHarddisk" Type="Double" /> <asp:Parameter Name="tblZip" Type="String" /> <asp:Parameter Name="tblCD" Type="String" /> <asp:Parameter Name="tblDVD" Type="String" /> <asp:Parameter Name="tblNetwerk" Type="String" /> <asp:Parameter Name="tblFirewire" Type="Int32" /> <asp:Parameter Name="tblAanschafdatum" Type="DateTime" /> <asp:Parameter Name="tblCLeverabcierNr" Type="Int32" /> <asp:Parameter Name="tblScherm" Type="String" /> <asp:Parameter Name="tblLaptop" Type="Boolean" /> </InsertParameters> </asp:SqlDataSource> This is the code of my FormView <asp:FormView ID="FormView1" runat="server" AllowPaging="True" DataKeyNames="tblArtveldenr" DataSourceID="sqldsLokaalPrinters"> <EditItemTemplate> tblPositie: <asp:TextBox ID="tblPositieTextBox" runat="server" Text='<%# Bind("tblPositie") %>' /> <br /> tblSerienr: <asp:TextBox ID="tblSerienrTextBox" runat="server" Text='<%# Bind("tblSerienr") %>' /> <br /> tblFabrikant: <asp:TextBox ID="tblFabrikantTextBox" runat="server" Text='<%# Bind("tblFabrikant") %>' /> <br /> tblModel: <asp:TextBox ID="tblModelTextBox" runat="server" Text='<%# Bind("tblModel") %>' /> <br /> tblSnelheid: <asp:TextBox ID="tblSnelheidTextBox" runat="server" Text='<%# Bind("tblSnelheid") %>' /> <br /> tblHarddisk: <asp:TextBox ID="tblHarddiskTextBox" runat="server" Text='<%# Bind("tblHarddisk") %>' /> <br /> tblCD: <asp:TextBox ID="tblCDTextBox" runat="server" Text='<%# Bind("tblCD") %>' /> <br /> tblDVD: <asp:TextBox ID="tblDVDTextBox" runat="server" Text='<%# Bind("tblDVD") %>' /> <br /> tblAanschafdatum: <asp:TextBox ID="tblAanschafdatumTextBox" runat="server" Text='<%# Bind("tblAanschafdatum") %>' /> <br /> <asp:LinkButton ID="UpdateButton" runat="server" CausesValidation="True" CommandName="Update" Text="Update" /> &nbsp;<asp:LinkButton ID="UpdateCancelButton" runat="server" CausesValidation="False" CommandName="Cancel" Text="Cancel" /> </EditItemTemplate> <InsertItemTemplate> tblPositie: <asp:TextBox ID="tblPositieTextBox" runat="server" Text='<%# Bind("tblPositie") %>' /> <br /> tblSerienr: <asp:TextBox ID="tblSerienrTextBox" runat="server" Text='<%# Bind("tblSerienr") %>' /> <br /> tblFabrikant: <asp:TextBox ID="tblFabrikantTextBox" runat="server" Text='<%# Bind("tblFabrikant") %>' /> <br /> tblModel: <asp:TextBox ID="tblModelTextBox" runat="server" Text='<%# Bind("tblModel") %>' /> <br /> tblSnelheid: <asp:TextBox ID="tblSnelheidTextBox" runat="server" Text='<%# Bind("tblSnelheid") %>' /> <br /> tblHarddisk: <asp:TextBox ID="tblHarddiskTextBox" runat="server" Text='<%# Bind("tblHarddisk") %>' /> <br /> tblCD: <asp:TextBox ID="tblCDTextBox" runat="server" Text='<%# Bind("tblCD") %>' /> <br /> tblDVD: <asp:TextBox ID="tblDVDTextBox" runat="server" Text='<%# Bind("tblDVD") %>' /> <br /> tblAanschafdatum: <asp:TextBox ID="tblAanschafdatumTextBox" runat="server" Text='<%# Bind("tblAanschafdatum") %>' /> <br /> <asp:LinkButton ID="InsertButton" runat="server" CausesValidation="True" CommandName="Insert" Text="Insert" /> &nbsp;<asp:LinkButton ID="InsertCancelButton" runat="server" CausesValidation="False" CommandName="Cancel" Text="Cancel" /> </InsertItemTemplate> <ItemTemplate> tblPositie: <asp:Label ID="tblPositieLabel" runat="server" Text='<%# Bind("tblPositie") %>' /> <br /> tblSerienr: <asp:Label ID="tblSerienrLabel" runat="server" Text='<%# Bind("tblSerienr") %>' /> <br /> tblFabrikant: <asp:Label ID="tblFabrikantLabel" runat="server" Text='<%# Bind("tblFabrikant") %>' /> <br /> tblModel: <asp:Label ID="tblModelLabel" runat="server" Text='<%# Bind("tblModel") %>' /> <br /> tblSnelheid: <asp:Label ID="tblSnelheidLabel" runat="server" Text='<%# Bind("tblSnelheid") %>' /> <br /> tblHarddisk: <asp:Label ID="tblHarddiskLabel" runat="server" Text='<%# Bind("tblHarddisk") %>' /> <br /> tblCD: <asp:Label ID="tblCDLabel" runat="server" Text='<%# Bind("tblCD") %>' /> <br /> tblDVD: <asp:Label ID="tblDVDLabel" runat="server" Text='<%# Bind("tblDVD") %>' /> <br /> tblAanschafdatum: <asp:Label ID="tblAanschafdatumLabel" runat="server" Text='<%# Bind("tblAanschafdatum") %>' /> <br /> <br /> <asp:LinkButton ID="EditButton" runat="server" CausesValidation="False" CommandName="Edit" Text="Edit" /> &nbsp;<asp:LinkButton ID="DeleteButton" runat="server" CausesValidation="False" CommandName="Delete" Text="Delete" /> &nbsp;<asp:LinkButton ID="NewButton" runat="server" CausesValidation="False" CommandName="New" Text="New" /> </ItemTemplate> </asp:FormView> I have no idea how to solve this error Thanks a lot Vincent

    Read the article

< Previous Page | 1 2