Need Help In SqlDataSource.Insert(); I Keep Getting An Error!!
Jan 4, 2007
Hello there,
I made a page to add these fields (name, description, price, end_date) into a SQL database. I'm using ASP.NET 2.0 with C#, my database is SQL 2005.
I did it without DetailsView or FormView, it consists of TextBoxes and a Calendar. Anyways, i wrote this code for Button1, which is the button that adds the data.
SqlDataSource sql = LoginView1.FindControl("SqlDataSource1") as SqlDataSource;
sql.Insert();
Response.Redirect("home.aspx");
}
The parameters and insert statments and commands are written from the SqlDataSource Insert Query wizard. But I keep getting this error when trying to click Button1.
Object must implement IConvertible.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.InvalidCastException: Object must implement IConvertible.
Source Error:
Line 31: {
Line 32: SqlDataSource sql = LoginView1.FindControl("SqlDataSource1") as SqlDataSource;
Line 33: sql.Insert();
Line 34: Response.Redirect("home.aspx");
Line 35: }
Source File: c:Documents and SettingsDoublethink..!!My DocumentsVisual Studio 2005WebSitesSunnDarkProjectsell.aspx.cs Line: 33
I have a database with columnsuserOwnListsuserID uniqueidentifieruserName nvarchar100userList nvrachar100createdDateI have created successfully a gridview controller to edit these values in database. The Gridview data is populated by SqlDataSource.I have also created a EmptyDataTemplate and created a form into it. There is only one textBox and submit button to create the First entry to userOwnLists -table.Now I collect the value from EmptyDataTemplate textbox with id userList1 and create a codebehind logic for the submitbutton.protected void Button2_Click(object sender, EventArgs e) { TextBox listName = (TextBox)this.FindControl("listName1", GridView1.Controls);SqlDataSource1.InsertParameters["userId"].DefaultValue = Membership.GetUser().ProviderUserKey; SqlDataSource1.InsertParameters["userName"].DefaultValue = Membership.GetUser().UserName.ToString(); SqlDataSource1.InsertParameters["listName"].DefaultValue = listName.Text; SqlDataSource1.InsertParameters["createdDate"].DefaultValue = DateTime.Now.ToString(); SqlDataSource1.Insert(); }The problem is now that I get error: Exception Details: System.Data.SqlClient.SqlException: Implicit conversion from data type sql_variant to uniqueidentifier is not allowed. Use the CONVERT function to run this query.OK. So I Googled a bit and found this:http://scottonwriting.net/sowblog/posts/4690.aspxMy Question is: How do I convert userId so I can insert it to database successfully?This does not work:String userId = Membership.GetUser().ProviderUserKey.ToString(); SqlDataSource1.InsertParameters["userId"].DefaultValue = Convert.ToString(userId);
What is the C# code I use to do this? I'm guessing it should be fairly simple, as there is only one row selected. I just need to pull out a specific field from that row and then insert that value into a different SqlDataSource.
Hello, I'm new to the forum and new to SQL, ASP.NET, etc. I am creating an intranet site for my company in VS 2005 and have run into a very annoying problem that I can't seem to solve. I have tried Googling it and came up empty. I have a database in SQL Express 2005 and my website will be accessing several tables within the database. I can retrieve info just fine and I can update, delete, etc just fine using gridview or other prebuilt tools, but when I add a few text boxes and wire a button to the SqlDataSource.Insert() command, I get a new record that is full of null values except for the identity key I have set. The kicker is that I am also using a master page and when I duplicate the web page without the master page link, everything works just fine. The following snippets show what I'm doing:<InsertParameters><asp:FormParameter Name="Name" Type="String" FormField="txtName" /><asp:FormParameter Name="Location" Type="String" FormField="ddlLocation" /><asp:FormParameter Name="Issue" Type="String" FormField="txtProblem" /></InsertParameters>Of course I match the formfields to the text boxes, create an onclick event for my button, the sqldatasource is configured correctly, it just doesn't work with the master page no matter what I do. Any help would be appreciated. Thanks
Hi,I am trying to insert data using data from a datalist on the page. To do this, I use the following coding: command.CommandText = "INSERT INTO Messages (sendername,recievername,message,Date,subject) VALUES (@sendername,@recievername,@message,@date,@subject)"; command.Parameters.AddWithValue("@sendername", System.Web.HttpContext.Current.User.Identity.Name); command.Parameters.AddWithValue("@recievername", SqlDataSource2 ); command.Parameters.AddWithValue("@message", TextBox2.Text); command.Parameters.AddWithValue("@subject", TextBox3.Text); command.Parameters.AddWithValue("@date", DateTime.Now.ToString()); command.ExecuteNonQuery(); SqlDataSource is the datasource for the other datalist- will this work?Thanks,Jon
Hi. I'm testing GridView and SqlDataSource controls and I'm using this http://msdn2.microsoft.com/en-us/library/system.web.ui.webcontrols.sqldatasource.insert.aspxI have problems with inserting new items into the db. As I understood from the code in that example, I need to create InsertParamaters and name it just like the one in the insert query. <asp:SqlDataSource ID="Sql1" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionString %>" SelectCommand="SELECT * FROM [Clients]" DeleteCommand="DELETE FROM [Clients] WHERE [ID] = @ID" InsertCommand="INSERT INTO [Clients] ([Name]) VALUES (@Name)" UpdateCommand="UPDATE [Clients] SET [Name] = @Name WHERE [ID] = @ID"> <DeleteParameters> <asp:Parameter Name="ID" Type="Int32" /> </DeleteParameters> <InsertParameters> <asp:ControlParameter Name="Name" ControlID="newClientTB" /> </InsertParameters> <UpdateParameters> <asp:Parameter Name="Name" Type="String" /> <asp:Parameter Name="ID" Type="Int32" /> </UpdateParameters> <InsertParameters> <asp:Parameter Name="Name" Type="String" /> </InsertParameters> </asp:SqlDataSource> and I get the following error when run:The variable name '@Name' has already been declared. Variable names must be unique within a query batch or stored procedure. Any help?
Coming from an asp world, I am totally lost on this one. I have two tables. tblUsers and tblUserInfo I have a gridview that gives me the list of users and when selected, it gives me the detailsview of the the record. However, When I need to add a new user, I am trying to add that user into tblUsers (which happens with no problems), and then add a record, using the same user number (UserID) has the key or ID for the tblUserInfo. So basicly, when I create a new user in tblUsers I want to create a record in tblUserInfo with the same userid. In ASP, this takes me minutes... I have been trying to figure this out for weeks. vs2005, sql express. Thanks.
Hi, I have some problem with inserting data into two separate table which are connected via foreign key like in this example:Students (id_s, name, id_subject)Subjects (id_subject, name)So the point is to add a new student and subject for that chosen student. You have to make two inserts right? but how to pass the primary key to the table with foreign key? The form consists of three texbox: name, name_of_subject. Both id_s and id_subject are increment automatically. Any idea how to do it? I would be very grateful for the working code.Thanks in advance and best regards,N.
Hey forum, the .NET form controls make it extremely easy to manage database data, control + SQLdatasource et voilĂ , its there. i have a web form, and a SQLdatasource with an insert query with parameters (works perfectly, only the Date picker Lite textbox ID as parameter wont register, but i have a thread runnin on their forums for that). when i open the Query builder and execute the query it works! woot! but now, how can i make it execute on a button press? i tried with several commands, like SQLdatasource1.execute, and several other commands i searched (can post later, not behind my test environment with my tools/webpage at the moment). so what is the command to let the SQLdatasource execute it's query? it's all i need to know to make several forms, please ghelp me! :) gr. michael
Hi all, I have few insertions statements in one datasource insert command, which i use for my user creation process adding new billing info shipping info and so on. I've put this code in createuserwizard usercreated step with a try catch code. On the insertion if it doesnt work it deletes the user account. Well lets say the first insertion went trough with out any problems, but the second one got blocked or didnt work length or any wierd on controled issue. I was thinking of putting begin transaction end transaction statements in front and end of the statements but this can prevent the insert not to return error, which will prevent try catch to fire? Basicly the idea is to do all insertions with the user creation, and if one goes down all the others gets reversed. (if possible single sqldatasource, just to make the code look clean)
Hello all, I am having problem to insert the record into database from sqldatasource control. my code is listed below, and i can't find anything why it cause the exception... <asp:SqlDataSource ID="SqlDataSource1" runat="server" DataSourceMode="DataSet" ConnectionString="<%$ ConnectionStrings:WebsiteDataConnection %>" SelectCommand="SELECT * FROM [ServiceAgents]" InsertCommand="INSERT INTO ServiceAgents VALUES(@Ser_STATE, @Ser_CITY, @Ser_AGENT, @Ser_PHONE, @Ser_EQUIPMENT)"> <InsertParameters> <asp:FormParameter Name="Ser_STATE" FormField="TextBox_state"/> <asp:FormParameter Name="Ser_CITY" FormField="TextBox_city"/> <asp:FormParameter Name="Ser_AGENT" FormField="TextBox_agent"/> <asp:FormParameter Name="Ser_PHONE" FormField="TextBox_phone"/> <asp:FormParameter Name="Ser_EQUIPMENT" FormField="TextBox_equip" /> </InsertParameters> </asp:SqlDataSource> The table has got the fields that needed for insert command, for example: <table> <tr> <td>State:</td> <td> <asp:TextBox ID="TextBox_state" runat="server"></asp:TextBox> <asp:RequiredFieldValidator id="RequiredFieldValidator1" runat="server" ControlToValidate="TextBox_state" Display="Static" ErrorMessage="Please enter a state." /> </td> </tr> <tr> <td>City:</td> <td> <asp:TextBox ID="TextBox_city" runat="server"></asp:TextBox> <asp:RequiredFieldValidator id="RequiredFieldValidator2" runat="server" ControlToValidate="TextBox_city" Display="Static" ErrorMessage="Please enter a city." /> </td> </tr> <tr> <td>Agent:</td> <td> <asp:TextBox ID="TextBox_agent" runat="server"></asp:TextBox> <asp:RequiredFieldValidator id="RequiredFieldValidator3" runat="server" ControlToValidate="TextBox_agent" Display="Static" ErrorMessage="Please enter a agent." /> </td> </tr> <tr> <td>Phone:</td> <td> <asp:TextBox ID="TextBox_phone" runat="server"></asp:TextBox> <asp:RequiredFieldValidator id="RequiredFieldValidator4" runat="server" ControlToValidate="TextBox_phone" Display="Static" ErrorMessage="Please enter a phone No." /> </td> </tr> <tr> <td>Equipment:</td> <td> <asp:TextBox ID="TextBox_equip" runat="server"></asp:TextBox> <asp:RequiredFieldValidator id="RequiredFieldValidator5" runat="server" ControlToValidate="TextBox_equip" Display="Static" ErrorMessage="Please enter a equipment." /> </td> </tr> <tr> <td></td> <td> <asp:Button ID="Button2" runat="server" Text="Add" OnClick="addEntry" BackColor="#FFFBFF" BorderColor="#CCCCCC" BorderStyle="Solid" BorderWidth="1px" Font-Names="Verdana" Font-Size="1.0em" ForeColor="#284775"/> </td> </tr> </table> And in the code i just called: SqlDataSource1.Insert(); Then the page gives me the exception like: Cannot insert the value NULL into column 'STATE', table 'WebsiteData.dbo.ServiceAgents'; column does not allow nulls. INSERT fails. The statement has been terminated. But i actually input all the required text in the textbox.... Any idea guys? Thanks
SqlDataSource UpdateCommand plus Insert I have a SqlDataSource with an UpdateCommand but besides that i need also an Insert command triggered on the same update command. That´s because i need to update a record and at the same time include a log of that update in another database. Thanks
I have a sqldatasource (code listed below) whose insert Paramaters are control parameters. My aspx page has a textbox and a submit button. the button onclick runs the sqdatasource1.insert. What I get is every other insert inserts the text in textbox2 and every other insert enters nothing for the namecust value. I have a required field validator which correctly prevents submission if textbox2 is empty. How do I fix this? :<code> <asp:Panel ID="Panel1" runat="server" Height="50px" Width="548px"> <asp:Button ID="Button1" runat="server" Text="New Prospect" ValidationGroup="insertCust" /> <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="TextBox2" ErrorMessage="Prospect Name can not be blank" ValidationGroup="insertCust"></asp:RequiredFieldValidator> <asp:TextBox ID="TextBox2" runat="server" Width="330px" ValidationGroup="insertCust"></asp:TextBox></asp:Panel> <asp:SqlDataSource ID="SqlDataSource2" runat="server" ConnectionString="<%$ ConnectionStrings:AccPac2ConnectionString %>" SelectCommand="SELECT DISTINCT CODETERR FROM dbo.F_arcus() AS F_arcus_1 WHERE (DATEINAC = 0) AND (rtrim(CODETERR) <>'')"> </asp:SqlDataSource> <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:AccPac2ConnectionString %>" InsertCommand="INSERT INTO dbo.BudgetProspects(NameCust, CodeTerr) VALUES (@Namecust, @codeterr)" SelectCommand="SELECT CustomerID, NameCust FROM dbo.BudgetProspects WHERE (CodeTerr = @codeterr)" UpdateCommand="UPDATE dbo.BudgetProspects SET NameCust = @namecust"> <UpdateParameters> <asp:Parameter Name="namecust" /> </UpdateParameters> <SelectParameters> <asp:ControlParameter ControlID="RadioButtonList1" Name="codeterr" PropertyName="SelectedValue" /> </SelectParameters> <InsertParameters> <asp:ControlParameter ControlID="textbox2" Name="Namecust" PropertyName="text" /> <asp:ControlParameter ControlID="RadioButtonList1" Name="codeterr" PropertyName="SelectedValue" /> </InsertParameters> </asp:SqlDataSource> </code> codebehind button_click: <code> Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click If Not TextBox2.Text Is Nothing Then SqlDataSource1.Insert() TextBox2.Text = "" End If End Sub </code>
I have a table with 2 columns - "memberid" is a guid and "Interest" is a string. In an aspx page I want to read in all values of "Interest" for a given "memberid" and display approprite checkboxes as checked. The user can then change which boxes are checked and I want to record the new list of selected items in the table. I created a SQLDataSource (see below) but when I run it, I get this error: ========== Error =========== Disallowed implicit conversion from data type sql_variant to data type uniqueidentifier, table 'DB_136571.dbo.gs_MemberInterests', column 'memberid'. Use the CONVERT function to run this query. ============================ The only use of this SQLDataSource is to delete all entries for a given user and then insert an entry for each checked checkbox. The code to set the session variables is as follows: ======== Code ============ Dim guidMemberid As Guid = CType(user.ProviderUserKey, Guid) Session("currmember") = guidMemberid ..... Session("currinterest") = CType(item.FindControl("CheckBox1"), CheckBox).Text ========================== Any ideas of what I am doing wrong here?
Hello, I have created a web page with a FormView that allows me to add and edit data in my database. I configured the SqlDataSource control and it populated the SELECT, INSERT, UPDATE and DELETE statements. I've created a stored procedure to do the INSERT and return to new identity value. My question is this: Can I configure the control to use this stored procedure? If so, how? Or do I have to write some code for one of the event handlers (inserting, updating???) Any help would be appreciated. -brian
hi i have an sqldatasource which has an insert command - a stored procedue is used.I have a text box with a button next to it . it is not in a datagrid.on the onclick event I would like to pass the value of the text box to the sqldatasource insert parameter ( it only expects this one parameter , and use the sqldatasource to do the insert basically doing a manual insert using the sqldatasource.does anyone know if this is possible thanks
I m trying to INSERT a record to my Consultants table using sqldatasource and formview: here is my sqldatasource code: <asp:SqlDataSource ID="sqlDS1" runat="server" ConnectionString="<%$ ConnectionStrings:myDB %>"InsertCommand="INSERT INTO [Consultants] ([firstName],[lastName],[skillCategoryID],[resourceManagerID],[AMgroupID],[skillSet],[statusID],[location],[comments],[profile],[isAvailable],[dateModified],[focusID]) VALUES (@FNAME, @LASTNAME, 1, @RESOURCEMANAGERID, @AMGROUPID, @SKILLSET, @STATUSID, @LOCATION,@COMMENTS,@PROFILE,@ISAVAILABLE,getdate(),1)">
<InsertParameters> <asp:FormParameter FormField="txtFName" Name="FNAME" /> <%--other parameters--%></InsertParameters></asp:SqlDataSource> now in my formview i have this:<asp:FormView DefaultMode="Insert" ID="FormView1" runat="server" DataSourceID="sqlDS1" DataKeyNames="id"> <table border="0" cellspacing="5" cellpadding="0"><tr> <td class="blacktextbold">First Name:</td> <td class="blacktext"><asp:TextBox ID="txtFName" CssClass="txtfield" Width="200" runat="server" Text="<% #Bind('firstName')%>" /> <asp:RequiredFieldValidator ControlToValidate="txtFName" runat="server" ValidationGroup="gpInsert" ErrorMessage="Required Field" Display="Dynamic" CssClass="redtextsmallbold" /> </td></tr> </table> THE PROBLEM:no matter what i put the txtFName field its ALWAYS null and i get INSERT error as column firstName cant accept NULLany ideas? ur help would be appreciated
Ok, when i use a sqldatasource control and build a INSERT command like below. My code always gives me a already have @UserId parameter error when I try to insert. What am I doing wrong here? SqlDataSource INSERT COMMAND:INSERT INTO Ranger_Profile(UserId, FirstName, LastName, Address, City, State, Zip, HomePhone, CellPhone, Email) VALUES (@UserId, @FirstName, @LastName, @Address, @City, @State, @Zip, @HomePhone, @CellPhone, @Email)Page Code:Dim RangerProfileDataSource As SqlDataSource = SqlDataSource1RangerProfileDataSource.InsertParameters.Add("UserId", CreateNewUser.UserName.ToString)RangerProfileDataSource.InsertParameters.Add("FirstName", txtFirstName.Text.ToString)RangerProfileDataSource.InsertParameters.Add("LastName", txtLastName.Text.ToString)RangerProfileDataSource.InsertParameters.Add("Address", txtAddress.Text.ToString)RangerProfileDataSource.InsertParameters.Add("City", txtCity.Text.ToString)RangerProfileDataSource.InsertParameters.Add("State", txtState.Text.ToString)RangerProfileDataSource.InsertParameters.Add("Zip", txtZip.Text.ToString)RangerProfileDataSource.InsertParameters.Add("HomePhone", txtHomePhone.Text.ToString)RangerProfileDataSource.InsertParameters.Add("CellPhone", txtCellPhone.Text.ToString)RangerProfileDataSource.InsertParameters.Add("Email", CreateNewUser.Email.ToString)Dim rowsaffected As Integer = SqlDataSource1.InsertIf rowsaffected = 0 Then'End If
Hi,because I have had problems with transporting of data from TextBoxes to SQL database in my application using SqlDataSource.Insert(), I tried to analyze it using Microsoft's sample code located here: http://msdn2.microsoft.com/en-us/library/system.web.ui.webcontrols.sqldatasource.insert.aspxEverything worked well untill I have used masterpage. Since this moment my database table started receive only NULL values - the same problem, which I have in my application. Despite all data values were correct before calling SqlDataSource.Insert() method. Is it some bug or something else (my bug ) and how can I resolve it? I'd like to use all advantages of masterpages and datasources together.Here are non-working codes of spoken sample:shelter3.aspx<%@ Page Language="VB" MasterPageFile="~/MasterPage3.master" AutoEventWireup="false" CodeFile="shelter3.aspx.vb" Inherits="shelter3" Title="Untitled Page" %><asp:Content ID="Content1" ContentPlaceHolderID="Obsah" runat="Server"><asp:DropDownList ID="DropDownList1" runat="server" DataSourceID="SqlDataSource1"DataTextField="nazev" DataValueField="code" /><asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:intranet %>"SelectCommand="SELECT nazev,code FROM smenky" InsertCommand="INSERT INTO smenky (nazev,code) VALUES (@nazev,@code)"><InsertParameters><asp:FormParameter Name="nazev" FormField="NazevBox" /><asp:FormParameter Name="code" FormField="CodeBox" /></InsertParameters></asp:SqlDataSource><p><asp:TextBox ID="NazevBox" runat="server" /><asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="NazevBox"Display="Static" ErrorMessage="Please enter a company name." /><p><asp:TextBox ID="CodeBox" runat="server" /><asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ControlToValidate="CodeBox"Display="Static" ErrorMessage="Please enter a phone number." /><p><asp:Button ID="Button1" runat="server" Text="Insert New Shipper" /></asp:Content> shelter3.aspx.vbPartial Class shelter3Inherits System.Web.UI.PageProtected Sub InsertShipper(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.ClickSqlDataSource1.Insert()End SubEnd Classmasterpage3.master<%@ Master Language="VB" CodeFile="MasterPage3.master.vb" Inherits="MasterPage3" %><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml" ><head runat="server"><title>Untitled Page</title></head><body><form id="form1" runat="server"><div><asp:contentplaceholder id="Obsah" runat="server"></asp:contentplaceholder></div></form></body></html>masterpage3.master.vbPartial Class MasterPage3Inherits System.Web.UI.MasterPageEnd ClassThanks for any idea
Hi all, I really can't figure out what i'm doing wrong here, and I'd appreciate some help if possible please! SqlDataSource5.InsertParameters("ntuser").DefaultValue = ntuser SqlDataSource5.InsertParameters("datetime").DefaultValue = DateTime.Now SqlDataSource5.Insert()Above is my code to insert into my SQL database a varchar NT user name, and the current date. The Parameters are defined in the HTML as : <asp:SqlDataSource ID="SqlDataSource5" runat="server" ConnectionString="<%$ ConnectionStrings:Test EnvironmentConnectionString %>" InsertCommand="usp_insert_hit" InsertCommandType="StoredProcedure" SelectCommand="usp_select_hits" SelectCommandType="StoredProcedure" UpdateCommand="usp_insert_hit" UpdateCommandType="StoredProcedure"> <InsertParameters> <asp:Parameter Name="ntuser" Type="String" /> <asp:Parameter Name="datetime" Type="DateTime" /> </InsertParameters></asp:SqlDataSource> My SQL Database is set up to have a table called "Hits" which has three colums, a hit_id (Autocounter, primary key), ntuser (varchar), datetime (datetime) When the application runs it stops at runtime and highlights the SQLDataSource5.Insert() line, and I can't figure out why - can anyone else tell why please? thanks.
I have a sqldatasource in a wizard. When I click the finishbutton in the wizard I want to insert some values (from textboxes, dropdownlists in my wizard) into a mysql-database. For this I use parameters, I add some values in the design mode and some in codebehind. The parameters in codebehind are added perfectly but the other parameters in designmode (name, email) just inserts null. Why? My datasource: <asp:SqlDataSource ID="dsInsert" InsertCommand="INSERT INTO tbltest (name, email, city) VALUES (?name, ?email, ?city)" runat="server" ConnectionString="<%$ ConnectionStrings:conn %>" ProviderName="MySql.Data.MySqlClient"> <InsertParameters> <asp:FormParameter Name="?name" ConvertEmptyStringToNull="true" Type="string" FormField="name" /> <asp:FormParameter Name="?email" ConvertEmptyStringToNull="true" Type="string" FormField="email" /> </InsertParameters> </asp:SqlDataSource> The codebehind: protected void finishButtonClick(object sender, EventArgs e) { dsInsert.InsertParameters.Add("?city", TypeCode.Int32, city.SelectedValue); dsInsert.Insert(); }
Hi frdz, I m the new user of ASP.NET WEB APPLICATIONS WITH C# LANGUAGE. I m using SQL SERVER 2005 and SQLDATASOURCE to get or retrieve the data from the database. I have created the stored procedure for insert and update. The stored procedure is executing fine when i m running it from sqlserver2005. My problem is with the web-application page. I m not able to insert or update data thru that... Pls check the code and tell me what's missing out ..........SQLDATASOURCE<asp:SqlDataSource ID="srcemp" runat="server" ConnectionString="<%$ ConnectionStrings:empmaster %>" InsertCommand="empStoredProcedure" InsertCommandType="StoredProcedure" UpdateCommand="empStoredProcedure" UpdateCommandType="StoredProcedure" DeleteCommand="DELETE FROM empmaster WHERE empid = @empid" DeleteCommandType="Text" SelectCommand="select * from empmaster " SelectCommandType="Text"> <InsertParameters><asp:Parameter Name="empname" Type="String" /><asp:Parameter Name="address" Type="String" /><asp:Parameter Name="city" /><asp:Parameter Name="pincode" /><asp:Parameter Name="state" /></InsertParameters> <UpdateParameters><asp:Parameter Name="empname" Type="String" /><asp:Parameter Name="address" Type="String" /><asp:Parameter Name="city" /><asp:Parameter Name="pincode" /><asp:Parameter Name="state" /></UpdateParameters> </asp:SqlDataSource>GRIDVIEW <asp:GridView ID="empGridView" runat="server" AutoGenerateColumns="False" DataKeyNames="empid" DataSourceID="srcemp" Width="56px" > <Columns> <asp:TemplateField> <ItemTemplate> <asp:LinkButton ID="btnDelete" runat="server" CommandName="Delete" OnClientClick="return confirm('Are you sure you want to delete this row ?');">Delete</asp:LinkButton> </ItemTemplate> </asp:TemplateField> <asp:boundfield datafield="empname" headertext="emp Name"/> <asp:boundfield datafield="address" headertext="Address"/> <asp:boundfield datafield="city" headertext="City"/> <asp:boundfield datafield="state" headertext="State"/> <asp:CheckBoxField DataField="deleted" HeaderText="In Existance" /> </Columns> </asp:GridView>C# code protected void cmdsubmit_Click(object sender, EventArgs e) { srcemp.InsertParameters["empname"].DefaultValue = tbcompanyname.Text; srcemp.InsertParameters["address"].DefaultValue = tbaddress.Text; srcemp.InsertParameters["city"].DefaultValue = tbcity.Text; srcemp.InsertParameters["pincode"].DefaultValue = tbpincode.Text; srcemp.InsertParameters["state"].DefaultValue = cmbstate.SelectedItem.ToString(); srcemp.Insert();}Note :I m not getting a single error msg for the above code in web-page or stored procedure but it does not insert,update or delete the record from the database....Thanxs in adv...pls reply at earliest if possible...What's missing ??can anyone check out..what's wrong ??
Hello! I have a SqlDataSource that inserts some data in a database. The field "id" is auto-increment. Is it possible to use the "id", this data-row got from the database automatically, directly after the SqlDataSource.Insert() command in my CodeBehind file? Thank you!
I'm a traditional asp guy and I'm having a heck of a time getting my arms around this SQLDataSource provided in ASP.NET 2.0 I've setup the Connection String and successfully used the SQLDataSource.Insert method. I can't for the life of me figure out how to use the SQLDataSource.Select command. I want to get the @@IDENTITY of the last record inserted. Example: ---Works Fine--- SQLDataSource.InsertCommand = "Insert into Engines(Type, Description)values('" & DrpType.Text & "', '" & txtDescription.Text & "')" SQLDataSource.Insert() --- End Works Fine------- Doesn't Work--- SQLDataSource.SelectCommand = "Select @@IDENTITY as 'Identity'" set RecordSetVar = SQLDataSource.Select <--- this wants some kind of arguements --- End Doesn't Work---
I apologise if i have not posted this in the correct Topic before i start. But was uncertain where to post this query. This is my first project in ASP.NET, MS Visual Web Developer 2005 Express and SQL Server 2005 Express. I have relatively little experience, so please bare with me. I have managed to create a form that inserts data into a table and then inserts the Automatically Created Primary Key(as a foreign key) in another table. I have done this by inserting what is highlighted in red in the code of my InsertCommand below (Please scroll across to the end of the code):-InsertCommand="INSERT INTO [PrinterModel] ([Model], [PrinterMakeID], [CartridgeCode], [PartCode], [Duplex], [NIC], [Wireless], [Parallel], [USB], [Colour], [PrinterTypeID]) VALUES (@Model, @PrinterMakeID, @CartridgeCode, @PartCode, @Duplex, @NIC, @Wireless, @Parallel, @USB, @Colour, @PrinterTypeID) INSERT INTO [Model] ([PrinterModelID],[TypeID]) VALUES (@@IDENTITY, 3)" Can you see any problems that may arise from using this method. This project is an Asset Management System and will be used by no more than a handful of users. My Concern is the use of the @@IDENTITY (As it only stores the last Key used). Should I be using it here? If there is more than one user inserting into tables (Chances of this happening are very low), will the correct Primary key be insert to the table in the above code?Thank you for your comments.
I’m trying to create a sqlDataSource using the wizard, I can get the select statement, the here clause and the order by clause but when I click on the Advanced button the options to generate the insert, update and delete statements are not available. Does anyone know what am I doing wrong?
i have default.aspx file and i put SqlDataSource into my designer form.when i want to configure SqlDataSource it not allowed my to insert, update and delete only insert is allowed.what is the problem and the solution for this case ...thx
I have a few columns in table with default value defined as zero length string (''). I want to insert record from DetailsView which uses SqlDataSource as DataSource. In the ItemInserting event, if the data is not valid, I want to use zero length string for the column. But I always get Null instead of zero length string. The code in ItemInserting event looks like this: If objddl.SelectedIndex > 0 Then e.Values("myFld") = objddl.SelectedItem.ValueElse e.Values("myFld") = ""End If The line: e.Values("myFld") = "" put Null in the column. How can I set a column as zero length string using the SqlDataSource? Any help is appreciated. Thanks.
Ok, this seems really straightforward, but I'm completely lost. I created a sqldatasource control that uses an INSERT stored procedure. I can click on test it tests just fine, inserts everything into the database.Now, I want this sqldatasource control to fire when a button is clicked, but I have no idea how to do this, I looked at the parameters and cant find an execute or anything like that to use. Let me know how to execute this sqldatasource, it'd really help me out. I know you can do EVERYTHING in the code behind file, but I'm rather new to VB and I'm probably gonna save that for another day. Here's what I have now:basic sqldatasource : <asp:SqlDataSource ID="SqlProcDS" runat="server" ConnectionString="<%$ ConnectionStrings:pubsConnectionString %>" InsertCommand="ins_test" InsertCommandType="StoredProcedure" SelectCommand="ins_test" SelectCommandType="StoredProcedure"> <SelectParameters> <asp:ControlParameter ControlID="TextBox1" Name="a" PropertyName="Text" Type="String" /> <asp:ControlParameter ControlID="TextBox2" Name="b" PropertyName="Text" Type="String" /> <asp:ControlParameter ControlID="TextBox3" Name="c" PropertyName="Text" Type="String" /> </SelectParameters> <InsertParameters> <asp:Parameter Name="a" Type="String" /> <asp:Parameter Name="b" Type="String" /> <asp:Parameter Name="c" Type="String" /> </InsertParameters> </asp:SqlDataSource>in the vb file : Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click 'Somehow execute sqlProcDS here?!End Sub