ASP.NET : SqlDataSource insert - identity parameter - c#

I have an asp.net application in which I am inserting into an sql table using a GridView linked to an SqlDataSource. The problem is that I do not know the 'Identity' parameter to use on insertion. The 'Identity' column should be automatically incrementing, however upon inserting, I get an exception that the Identity param must not be null. How do I either craft the insert statement so that this works or how do I get the next correct identity # to specify? Thanks.
Here is my SqlDataSource code:
<asp:SqlDataSource ID="VehiclesSqlDS" runat="server"
ConnectionString="<%$ ConnectionStrings:RamRideOpsConnectionString %>"
SelectCommand="SELECT * FROM [Vehicles]"
ConflictDetection="CompareAllValues"
InsertCommand="INSERT INTO [Vehicles] ([Identity], [CarNum], [MaxPassengers], [Status], [CurrPassengers], [StartAdd], [EndAdd], [AvgRideTime], [numRides]) VALUES (#Identity, #CarNum, #MaxPassengers, #Status, #CurrPassengers, #StartAdd, #EndAdd, #AvgRideTime, #numRides)"
OnInserting="VehiclesSqlDS_Insert"
OldValuesParameterFormatString="original_{0}">
<InsertParameters>
<asp:Parameter Name="Identity" Type="Int32 "/>
<asp:Parameter Name="CarNum" Type="Int32" DefaultValue="-1"/>
<asp:Parameter Name="MaxPassengers" Type="Int32" DefaultValue="3" />
<asp:Parameter Name="Status" Type="String" DefaultValue="Ready" />
<asp:Parameter Name="CurrPassengers" Type="Int32" DefaultValue="0" />
<asp:Parameter Name="StartAdd" Type="String" />
<asp:Parameter Name="EndAdd" Type="String" />
<asp:Parameter DbType="Time" Name="AvgRideTime" />
<asp:Parameter Name="numRides" Type="Int32" DefaultValue="0" />
</InsertParameters>
</asp:SqlDataSource>

you need to set parameter direction to OUTPut, to get the identity value. from MSDN
and handle the onInserted event to get, the identity value
protected void SqlDataSource1_Inserted(object sender, SqlDataSourceStatusEventArgs e)
{
string sID = e.Command.Parameters["#Identity"].Value.ToString();
//Display new ID
}
you can try like this.
<asp:sqlDataSource ID="Datasource"
SelectCommand="SELECT EmployeeID, LastName, FirstName FROM Employees WHERE EmployeeID = #EmpID"
InsertCommand="INSERT INTO Employees(LastName, FirstName) VALUES (#LastName, #FirstName);
SELECT #EmpID = SCOPE_IDENTITY()"
UpdateCommand="UPDATE Employees SET LastName=#LastName, FirstName=#FirstName
WHERE EmployeeID=#EmployeeID"
DeleteCommand="DELETE Employees WHERE EmployeeID=#EmployeeID"
ConnectionString="<%$ ConnectionStrings:NorthwindConnection %>"
OnInserted="EmployeeDetailsSqlDataSource_OnInserted"
RunAt="server">
<SelectParameters>
<asp:Parameter Name="EmpID" Type="Int32" DefaultValue="0" />
</SelectParameters>
<InsertParameters>
<asp:Parameter Name="EmpID" Direction="Output" Type="Int32" DefaultValue="0" />
</InsertParameters>
</asp:sqlDataSource>

You should omit the Identity column from the insert statement. Only include the data columns. The Sql Server will create the auto-increment then.
INSERT INTO [Vehicles] ([CarNum], [MaxPassengers], [Status], [CurrPassengers], [StartAdd], [EndAdd], [AvgRideTime], [numRides]) VALUES (#CarNum, #MaxPassengers, #Status, #CurrPassengers, #StartAdd, #EndAdd, #AvgRideTime, #numRides)

Ever Present, that is assuming that Identity is an auto-incremeneted column. It could just be a regular column.
You need to somehow retrieve the latest Identity first before trying to insert.
Alternatively you could write a trigger on the database that automatically updates the Identity column when a new item is added.

These snippets may help:
<InsertParameters>
<asp:Parameter Name="SalesRepID" Type="Int32" />
...more params
<asp:Parameter Name="QuoteID" Type="Int32" Direction="Output" />
</InsertParameters>
Note the second command added
InsertCommand="INSERT INTO [MyTable] (fields); SET #QuoteID = Scope_Identity();"

Related

Default value in select parameter as DateTime.Now

I'm trying set default value of select parameter in MVC:
<asp:Parameter Name="PickDate" Type="DateTime" DefaultValue="<%: DateTime.Now.ToString("yyyy-MM-dd")%>" />
But it doesn't work... I got error":
String was not recognized as a valid DateTime.
Can I set DateTime.Now to default value?
Edit1: Still doesn't work...
<asp:SqlDataSource ID="SqlDataSourceDailyPickingList" runat="server"
ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
ProviderName="<%$ ConnectionStrings:ConnectionString.ProviderName %>"
SelectCommand="SELECT * FROM DailyPickingList where PickDate = #PickDate">
<SelectParameters>
<asp:Parameter Name="PickDate" Type="DateTime" DefaultValue="<%: DateTime.Now%>" />
</SelectParameters>
</asp:SqlDataSource>
Is it at all possible ?
You are casting to string the default value when explicitly setting the type as DateTime. Try this:
<asp:Parameter Name="PickDate" Type="DateTime" DefaultValue="<%: DateTime.Now%>" />
Or this
<asp:Parameter Name="PickDate" Type="string" DefaultValue='<%: DateTime.Now.ToString("yyyy-MM-dd")%>' />

GridView update/delete crashes

I have a gridview of my table. I established a AccsessDataSource to my database. The Accsess datasource is configured so the sql scentance is: SELECT * FROM [Users] In the advanced settings I checked "Generate INSERT, UPDATE, and delete statements" I enabled editing and deleting. My source code shows this:
<asp:AccessDataSource ID="AccessDataSource2" runat="server" DataFile="~/App_Data/RunRunDB.mdb"
DeleteCommand="DELETE FROM [Users] WHERE (([username] = ?) OR ([username] IS NULL AND ? IS NULL))"
InsertCommand="INSERT INTO [Users] ([Fname], [Lname], [Email], [Bday], [pswrd], [admin], [username]) VALUES (?, ?, ?, ?, ?, ?, ?)"
OldValuesParameterFormatString="original_{0}"
SelectCommand="SELECT * FROM [Users]"
UpdateCommand="UPDATE [Users] SET [Fname] = ?, [Lname] = ?, [Email] = ?, [Bday] = ?, [pswrd] = ?, [admin] = ? WHERE (([username] = ?) OR ([username] IS NULL AND ? IS NULL))">`
<DeleteParameters>
<asp:Parameter Name="original_username" Type="String" />
</DeleteParameters>
<InsertParameters>
<asp:Parameter Name="Fname" Type="String" />
<asp:Parameter Name="Lname" Type="String" />
<asp:Parameter Name="Email" Type="String" />
<asp:Parameter Name="Bday" Type="DateTime" />
<asp:Parameter Name="pswrd" Type="String" />
<asp:Parameter Name="admin" Type="Boolean" />
<asp:Parameter Name="username" Type="String" />
</InsertParameters>
<UpdateParameters>
<asp:Parameter Name="Fname" Type="String" />
<asp:Parameter Name="Lname" Type="String" />
<asp:Parameter Name="Email" Type="String" />
<asp:Parameter Name="Bday" Type="DateTime" />
<asp:Parameter Name="pswrd" Type="String" />
<asp:Parameter Name="admin" Type="Boolean" />
<asp:Parameter Name="original_username" Type="String" />
</UpdateParameters>
</asp:AccessDataSource>
Each time i run my website i get an error that says: You do not have a value for one or more of the required parameters.
Thanks..
Your problem is here:
WHERE (([username] = ?) OR ([username] IS NULL AND ? IS NULL))
Command parameters cannot be used to specify table or column (field) names; they only specify column values. You will have to adjust your UpdateCommand and DeleteCommand strings to specify the column name explicitly.

How can I use a DropDownList to limit user selection in a Database INSERT?

I am trying to limit the selection of an INSERT using a DropDownList, my TextBox all work correctly but I cannot seem to figure out how to use a DropDownList in a similar fashion.
Here is my current code-behind:
private void _subInsert(RepeaterCommandEventArgs e)
{
TextBox txtPostTitle = (TextBox)e.Item.FindControl("txt_post_titleI"); // Find the control with the information you wish to store
TextBox txtPostBody = (TextBox)e.Item.FindControl("txt_post_bodyI");
TextBox txtPostAuthor = (TextBox)e.Item.FindControl("txt_post_authorI");
DropDownList ddlPostType = (DropDownList)e.Item.FindControl("ddl_post_typeI");
sds_main.InsertParameters["post_title"].DefaultValue = txtPostTitle.Text; // Insert information into this location in the DB
sds_main.InsertParameters["post_body"].DefaultValue = txtPostBody.Text;
sds_main.InsertParameters["post_author"].DefaultValue = txtPostAuthor.Text;
sds_main.InsertParameters["post_type"].DefaultValue = ddlPostType.SelectedValue.ToString();
sds_main.Insert(); // Perform Insert
}
The TextBoxes all insert correctly, but the DropDownList does not allow me to use the SelectedValue in the Insert. I am getting a "Object reference not set to an instance of an object." error.
This is the code for my SQLDataSource control on the presentation page:
<asp:SqlDataSource
id="sds_main"
runat="server"
ConnectionString="<%$ ConnectionStrings:fntn0070DBConnectionString %>"
SelectCommand="SELECT * FROM [blogTest]"
DeleteCommand="DELETE FROM [blogTest] WHERE [id] = #id"
InsertCommand="INSERT INTO [blogTest] ([post_title], [post_body], [post_author], [post_type]) VALUES (#post_title, #post_body, #post_author, #post_type)"
UpdateCommand="UPDATE [blogTest] SET [post_title] = #post_title, [post_body] = #post_body, [post_author] = #post_author, [post_type] = #post_type WHERE [id] = #id" >
<DeleteParameters>
<asp:Parameter Name="id" Type="Int32" />
</DeleteParameters>
<InsertParameters>
<asp:Parameter Name="post_title" Type="String" />
<asp:Parameter Name="post_body" Type="String" />
<asp:Parameter Name="post_date" Type="String" />
<asp:Parameter Name="post_author" Type="String" />
<asp:Parameter Name="post_type" Type="String" />
</InsertParameters>
<UpdateParameters>
<asp:Parameter Name="post_title" Type="String" />
<asp:Parameter Name="post_body" Type="String" />
<asp:Parameter Name="post_author" Type="String" />
<asp:Parameter Name="post_type" Type="String" />
<asp:Parameter Name="id" Type="Int32" />
</UpdateParameters>
</asp:SqlDataSource>
And this is my DDL on the presentation page:
<asp:DropDownList ID="ddl_postTypeI" runat="server">
<asp:ListItem>Web Development</asp:ListItem>
<asp:ListItem>Photography</asp:ListItem>
<asp:ListItem>Other</asp:ListItem>
</asp:DropDownList>
I have tried my best to search for this problem on Google and StackOverflow but have only be able to find information on how to bind data to the DDL.
I am very new to ASP.NET 4, just starting to learn it in my web development course so please ELI5 if you are able to answer. Thanks in advance for any help you are able to provide.
you can not use it directly without giving value of dropdown list.
try this
<asp:DropDownList ID="ddl_postTypeI" runat="server">
<asp:ListItem Value="Web Development">Web Development</asp:ListItem>
<asp:ListItem Value="Photography">Photography</asp:ListItem>
<asp:ListItem Value="Other">Other</asp:ListItem>
</asp:DropDownList>
and then try to insert in data , if you are passing integer value then use value="1" otherwise it will throw an error.
Thanks,

DetailsView update

I have a GridView that shows all the registed users and some of their information and when you choose the "select" link off the side, it shows a DetailsView with all the details related to that user. The select works fine and updates the details view for the selected user, and when I try to edit the DetailsView, it will update the database and fill in the information updated for ALL the users when changing the fields (eg. if I change the customers first name, everyone registered will get that name). Here's my aspx code for my SqlDataSource:
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:ApplicationServices %>" OldValuesParameterFormatString="original_{0}"
SelectCommand="SELECT * FROM [UserProfile] ORDER BY [Email], [LastName], [Company]"
UpdateCommand="UPDATE [UserProfile] SET [LastName] = #LastName, [PartsList] = #PartsList, [UserName] = #UserName, [Question] = #Question,
[Answer] = #Answer, [Role] = #Role
WHERE [FirstName] = FirstName AND [Company] = Company">
<UpdateParameters>
<asp:Parameter Name="FirstName" Type="String" />
<asp:Parameter Name="LastName" Type="String" />
<asp:Parameter Name="Company" Type="String" />
<asp:Parameter Name="PartsList" Type="String" />
<asp:Parameter Name="UserName" Type="String" />
<asp:Parameter Name="Password" Type="String" />
<asp:Parameter Name="Email" Type="String" />
<asp:Parameter Name="Question" Type="String" />
<asp:Parameter Name="Answer" Type="String" />
<asp:Parameter Name="Role" Type="String" />
</UpdateParameters>
</asp:SqlDataSource>
You forgot #original_ in your Where parameters
Change UpdateCommand to:
UPDATE [UserProfile] SET [LastName] = #LastName, [PartsList] = #PartsList, [UserName] = #UserName, [Question] = #Question,
[Answer] = #Answer, [Role] = #Role
WHERE [FirstName] = #original_FirstName AND [Company] = #original_Company

Insert proper phone format

I have a textbox which stores phone number.
<asp:TextBox runat="server" ID="phone" MaxLength="10" Columns="10" Width="90px" />
<asp:MaskedEditExtender ID="phone_MaskedEditExtender" runat="server" CultureAMPMPlaceholder=""
CultureCurrencySymbolPlaceholder="" CultureDateFormat="" CultureDatePlaceholder=""
CultureDecimalPlaceholder="" CultureThousandsPlaceholder="" CultureTimePlaceholder=""
Enabled="True" TargetControlID="phone" Mask="(999)-999-9999" ClearMaskOnLostFocus="False">
</asp:MaskedEditExtender>
The question is when I insert phone number 9999999999, the number in the database becomes
(999)-9999.
What I want is 9999999999.
The other code is:
<asp:SqlDataSource ID="InsertExtraInfo" runat="server" ConnectionString="<%$ ConnectionStrings:MembershipDB %>"
InsertCommand="CreateAdditionalAccountInfo" InsertCommandType="StoredProcedure">
<InsertParameters>
<asp:ControlParameter Name="FirstName" Type="String" ControlID="FirstName" PropertyName="Text" />
<asp:ControlParameter Name="LastName" Type="String" ControlID="LastName" PropertyName="Text" />
<asp:ControlParameter Name="Degree" Type="String" ControlID="Degree" PropertyName="Text" />
<asp:ControlParameter Name="Organization" Type="String" ControlID="Organization"
PropertyName="Text" />
<asp:ControlParameter Name="Phone" Type="String" ControlID="Phone" PropertyName="Text" />
<asp:ControlParameter Name="Ext" Type="String" ControlID="Ext" PropertyName="Text" />
<asp:ControlParameter Name="last4SSN" Type="String" ControlID="TextSSN" PropertyName="Text" />
</InsertParameters>
</asp:SqlDataSource>
The stored Procedure query is
INSERT INTO [User_ExtraInfo] ([UserId], [FirstName], [LastName], [Degree], [Organization], [Phone], [Ext], [last4SSN],[Trained]) VALUES (#UserId, #FirstName, #LastName, #Degree, #Organization, #Phone, #Ext
Thanks.
Change the proc to this:
INSERT INTO [User_ExtraInfo] ([UserId], [FirstName], [LastName], [Degree], [Organization], [Phone], [Ext], [last4SSN],[Trained]) VALUES (#UserId
, #FirstName
, #LastName
, #Degree
, #Organization
, REPLACE(REPLACE( REPLACE(#Phone,'(',''),')','') ,'-','') , #Ext )
The reason I suggest this approach is because you are using a SQLDatasource object and I don't think it's possible to instruct the insert parameter -at least not declaratively from the markup- to ignore the mask. Your best bet is probably just to modify the proc.
UPDATE - programmatic approach:
Add a handler for OnInserting to the SqlDataSource:
<asp:SqlDataSource ID="InsertExtraInfo" runat="server" OnInserting="On_Inserting"
Handle the event on code and do the replacement there:
protected void On_Inserting(Object sender, SqlDataSourceCommandEventArgs e) {
e.Command.Parameters["#Phone"].Value=phone.Text.Replace("..."); // etc
}
Note: not tested but it's the idea.

Categories

Resources