I have an SqlDataSource attached to a FormView which is used for inserting/updating, which used to work perfectlly - but now all of a sudden, none of the parameters are inserted into the row (the row is still created with error, but all the fields except ID are null). I have double checked to make sure all correct textbox's are bound to the column name and they are.
I'm just wondering what sort of problems can cause this as I'm stumped. I've attached to the DataBound method of the formview just to make sure the form isn't being rebound on postback and it isn't. I've also checked out the Inserting method and the parameters are all null there.
EDIT: Here's the datasource markup:
<asp:SqlDataSource runat='server' ID='dsOrders' ConnectionString="<%$ ConnectionStrings:WebConnectionString %>"
SelectCommand="SELECT Orders.ID, Orders.Created, Orders.ReportingCat, Orders.OrderType, Orders.Customer, Orders.Reference, Orders.RequiredDate, Contacts.ContactName AS 'ContactName', ISNULL(Orders.Collection, 0) AS 'Collection', Orders.DirectToSite, Orders.OnSite, Orders.DelAdd1, Orders.DelAdd2, Orders.DelAdd3, Orders.DelTown, Orders.DelCounty, Orders.DelPostCode, Orders.Carriage, Orders.CarriageAmount, Orders.CarriageOverrideNote, Orders.SalesPerson, Orders.Offload, Orders.DelTimeBegin, Orders.DelTimeEnd, Orders.DeliveryInstruction, Orders.SpecialInstruction, Orders.AccountsNote, Orders.Status, SalesPeople.FirstName + ' ' + CASE WHEN SalesPeople.Surname IS NULL THEN '' ELSE SalesPeople.Surname END AS SalesName, ISNULL(Orders.ContactID, '') AS ContactID, Orders.OrderNumber, Orders.QuoteNumber, Orders.CustomerOrderLink, ISNULL(Orders.ProjectDetails, 0) AS 'ProjectDetails', Orders.SalesPersonContact, Orders.DeliveryCharge, Orders.SiteName, Orders.MainContractor, Orders.Address, Orders.Town, Orders.County, Orders.Postcode FROM Orders LEFT OUTER JOIN SalesPeople ON Orders.SalesPerson = SalesPeople.ID LEFT OUTER JOIN Contacts ON Orders.ContactID = Contacts.ContactID WHERE (Orders.ID = #Order ) OR ( #Order IS NULL)"
InsertCommand="INSERT INTO Orders(Customer, Collection, SalesPerson, Offload, Status, ContactID, OrderNumber, QuoteNumber, ProjectDetails, SalesPersonContact, DeliveryCharge) VALUES (#Customer, #Collection, #SalesPerson, #Offload, 1, #ContactID, #OrderNumber, #QuoteNumber, #ProjectDetails, #SalesPersonContact, #DeliveryCharge); SET #ReturnID = SCOPE_IDENTITY();"
OnInserted="dsOrders_Inserted" OnInserting="dsOrders_Inserting" UpdateCommand="UPDATE Orders SET Customer = #Customer, Collection = #Collection, SalesPerson = #SalesPerson, Offload = #Offload, ContactID = #ContactID, OrderNumber = #OrderNumber, QuoteNumber = #QuoteNumber, ProjectDetails = #ProjectDetails, SalesPersonContact = #SalesPersonContact, DeliveryCharge = #DeliveryCharge WHERE (ID = #ID)">
<UpdateParameters>
<asp:Parameter Name="Customer" Type="String" />
<asp:Parameter Name="Collection" Type="Boolean" />
<asp:Parameter Name="SalesPerson" Type="Int32" />
<asp:Parameter Name="Offload" Type="Boolean" />
<asp:Parameter Name="ContactID" Type="Int64" />
<asp:Parameter Name="OrderNumber" Type="Int64" />
<asp:Parameter Name="QuoteNumber" Type="String" />
<asp:Parameter Name="ProjectDetails" Type="Boolean" />
<asp:Parameter Name="SalesPersonContact" Type="Int64" />
<asp:Parameter Name="DeliveryCharge" Type="Int32" />
<asp:SessionParameter Name="ID" SessionField="OrderID" Type="Int64" />
</UpdateParameters>
<InsertParameters>
<asp:Parameter Name="Customer" Type="String" />
<asp:Parameter Name="Collection" Type="Boolean" />
<asp:Parameter Name="SalesPerson" Type="Int32" />
<asp:Parameter Name="Offload" Type="Boolean" />
<asp:Parameter Name="ContactID" Type="Int64" />
<asp:Parameter Name="OrderNumber" Type="Int64" />
<asp:Parameter Name="QuoteNumber" Type="String" />
<asp:Parameter Name="ProjectDetails" Type="Boolean" />
<asp:Parameter Name="SalesPersonContact" Type="Int64" />
<asp:Parameter Name="DeliveryCharge" Type="Int32" />
<asp:Parameter Name="ReturnID" Direction="Output" Type="Int64" />
</InsertParameters>
<SelectParameters>
<asp:SessionParameter DefaultValue="null" Name="Order" SessionField="OrderID" />
</SelectParameters>
</asp:SqlDataSource>
In your INSERT command I cannot see ID:
INSERT INTO Orders(Customer, Collection, SalesPerson, Offload, Status, ContactID,
OrderNumber, QuoteNumber, ProjectDetails, SalesPersonContact, DeliveryCharge) VALUES
(#Customer, #Collection, #SalesPerson, #Offload, 1, #ContactID, #OrderNumber, #QuoteNumber,
#ProjectDetails, #SalesPersonContact, #DeliveryCharge);
Related
I'm using asp.net 4.5 and c# for my codebehind
I have a SqlDataSource that is not bound to a control; the purpose is - based on an action button i'll call a stored procedure. (I have another sqldatasource that fills a table, based on clicking a button w/in a row of that gridview the SP is supposed to execute using parameters from the gridview)
I've messed around with the definition of the data source
My questions/plea for help are:
Is my SP being called at all with DataBind ? (and maybe my parameters are ill formed) - or does it need an object on the asp page to be tied to? Is there a better way to call the sp?
How do I get/see the ReturnValue?
How can I see the SQL output? (or maybe I should just make that an input/output parameter of the SP)
Advance thanks for any help.
((latest version of asp sql source - with exec and parms in the select))
<asp:SqlDataSource ID="sqlAlterStatus" runat="server" ConnectionString="<%$ ConnectionStrings:BOS_data.Prod %>"
SelectCommand="EXEC #ReturnValue = Customer_Contact_output.sp_PCC_Channel_Strategy_ltrs_alter_action_campaign_wth #FILE_ID, #Campaign_Name, #UPSCheck, #ACTION, #ECODE, #FULLNAME"
SelectCommandType="StoredProcedure">
<SelectParameters>
<asp:Parameter Name="FILE_ID" Type="Int32" />
<asp:Parameter Name="Campaign_Name" Type="String" />
<asp:Parameter Name="UPSCheck" Type="Boolean" />
<asp:Parameter Name="ACTION" Type="Byte" />
<asp:Parameter Name="ECODE" Type="String" />
<asp:Parameter Name="FULLNAME" Type="String" />
<asp:Parameter Name="ReturnValue" Type="Int16" Direction="ReturnValue" />
</SelectParameters>
</asp:SqlDataSource>
((and my original - parms not in select))
<asp:SqlDataSource ID="sqlAlterStatus" runat="server" ConnectionString="<%$ ConnectionStrings:BOS_data.Prod %>"
SelectCommand="Customer_Contact_output.sp_PCC_Channel_Strategy_ltrs_alter_action_campaign_wth" SelectCommandType="StoredProcedure">
<SelectParameters>
<asp:Parameter Name="FILE_ID" Type="Int32" />
<asp:Parameter Name="Campaign_Name" Type="String" />
<asp:Parameter Name="UPSCheck" Type="Boolean" />
<asp:Parameter Name="ACTION" Type="Byte" />
<asp:Parameter Name="ECODE" Type="String" />
<asp:Parameter Name="FULLNAME" Type="String" />
<asp:Parameter Name="ReturnValue" Type="Int16" Direction="ReturnValue" />
</SelectParameters>
</asp:SqlDataSource>
The SP is mostly simple - definition:
ALTER PROCEDURE [Customer_Contact_output].[sp_PCC_Channel_Strategy_ltrs_alter_action_campaign_wth]
#FILE_ID BIGINT
, #Campaign_Name VARCHAR(50)
, #UPSCheck BIT
, #ACTION TINYINT
, #ECODE VARCHAR(6)
, #FULLNAME VARCHAR(255)
after validation/updates/inserts there is a simple select (for a message - which I can't figure how to capture either) and return value -- like this:
SELECT 'FAIL - INVALID PARAMETER (CAMPAIGN NAME)' AS RETURN_MESSAGE
RETURN 0 -- FAIL
I'm trying to call the SP from the RowCommand on the gridview ((I've also altered this a bunch of times ... mostly in setting the parms: I've used both .DefaultValue = something :: and .Equals(something)
protected void grdPCCletters_RowCommand(object sender, GridViewCommandEventArgs e)
{
// for the SP
string strSuppress = "1";
string strRelease = "8";
// get all the variables for the stored procedure call
string strCampaign = grdPCCletters.Rows[int.Parse(e.CommandArgument.ToString())].Cells[3].Text;
//string strUPS = grdPCCletters.Rows[int.Parse(e.CommandArgument.ToString())].Cells[4].Text;
bool boolUPS = Convert.ToBoolean(grdPCCletters.Rows[int.Parse(e.CommandArgument.ToString())].Cells[4].Text);
int intCurrStatus = Convert.ToInt16(grdPCCletters.Rows[int.Parse(e.CommandArgument.ToString())].Cells[8].Text);
Int64 intFileID = Convert.ToInt64( grdPCCletters.Rows[int.Parse(e.CommandArgument.ToString())].Cells[9].Text);
string strFullName = grdPCCletters.Rows[int.Parse(e.CommandArgument.ToString())].Cells[10].Text;
string strEcode = grdPCCletters.Rows[int.Parse(e.CommandArgument.ToString())].Cells[11].Text;
//int intReturnValue; --- GRRR, how to get the returnvalue from the sp??
// sqlAlterStatus.SelectParameters.UpdateValues
// these values apply regardless of the action
sqlAlterStatus.SelectParameters["FILE_ID"].DefaultValue = intFileID.ToString();
sqlAlterStatus.SelectParameters["Campaign_Name"].DefaultValue = strCampaign;
sqlAlterStatus.SelectParameters["UPSCheck"].DefaultValue = Convert.ToInt16(boolUPS).ToString();
sqlAlterStatus.SelectParameters["ECODE"].DefaultValue = strEcode;
sqlAlterStatus.SelectParameters["FULLNAME"].DefaultValue = strFullName;
{
if (e.CommandName.ToString() == "Suppress")
{
//sqlAlterStatus - set parameters
sqlAlterStatus.SelectParameters["ACTION"].DefaultValue = (Convert.ToInt16(strSuppress)).ToString();
// execute SP
sqlAlterStatus.DataBind();
//intReturnValue = sqlAlterStatus.SelectParameters["ReturnValue"].ToString();
}
else if (e.CommandName.ToString() == "Release")
{
//sqlAlterStatus
sqlAlterStatus.SelectParameters["ACTION"].Equals(Convert.ToInt16(strRelease));
sqlAlterStatus.DataBind();
}
}
}
OMG . what a ... the one parameter is a Boolean, and I tried to be smarter than visual studio ... I converted the t/f to a 1/0 to call the SP (cuz, well, that's how I'd call in SQL directly!)
changing it to:
sqlAlterStatus.SelectParameters["UPSCheck"].DefaultValue = boolUPS.ToString();
made it work -- good grief
Oh, and in my flipping back and forth, it also wouldn't work without something to be bound to .. like a form. :(
I wanted to insert a variable into a table in db using the SqlDataSource. Below is my code in aspx:
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:ACM_DBConnectionString %>"
DeleteCommand="DELETE FROM [ContestRelation] WHERE [relationid] = #relationid"
InsertCommand="INSERT INTO [ContestRelation] ([contestid]) VALUES (#contestid)"
SelectCommand="SELECT [relationid], [contestid] FROM [ContestRelation]"
UpdateCommand="UPDATE [ContestRelation] SET [contestid] = #contestid WHERE [relationid] = #relationid">
<DeleteParameters>
<asp:Parameter Name="relationid" Type="Int32" />
</DeleteParameters>
<InsertParameters>
<asp:Parameter Name="contestid" Type="Int32" />
</InsertParameters>
<UpdateParameters>
<asp:Parameter Name="contestid" Type="Int32" />
<asp:Parameter Name="relationid" Type="Int32" />
</UpdateParameters>
</asp:SqlDataSource>
and the code behind:
protected void ConfirmContest_Click(object sender, EventArgs e)
{
try
{
foreach (GridItem item in RadGrid1.MasterTableView.Items)
{
GridDataItem dataitem = (GridDataItem)item;
TableCell cell = dataitem["selectContest"];
CheckBox checkBox = (CheckBox)cell.Controls[0];
if (checkBox.Checked)
{
string value = dataitem.GetDataKeyValue("contestid").ToString();
SqlDataSource1.InsertParameters.Add("contestid", value);
SqlDataSource1.Insert();
}
}
}
catch (Exception ex)
{
Response.Write("<script language='javascript'>alert('No data selected .');</script>");
}
}
The "value" variable is not inserted into the database table. Can anyone point me my mistakes? Thanks in advance.
Problem Solved!
I actually cannot add an existing insert parameter, instead, I change to following code
string value = dataitem.GetDataKeyValue("contestid").ToString();
SqlDataSource1.InsertParameters.Add("contestid", value);
SqlDataSource1.Insert();
to following code. And the problem is solved.
string value = dataitem.GetDataKeyValue("contestid").ToString();
SqlDataSource1.InsertParameters["contestid"].DefaultValue = value;
SqlDataSource1.Insert();
I have a stored procedure to search in my book table :
ALTER PROCEDURE dbo.book_serchbook
#CategoryID int,#BookTitle nvarchar(100) ,
#CategoryName nvarchar (100) ,
#AuthorName nvarchar(100),
#PublisherName nvarchar(100)
AS
SELECT DISTINCT
BookTable.BookID, BookTable.BookCover
FROM
BookTable
INNER JOIN
CategoryTable ON CategoryTable.CategoryID = BookTable.CategoryID
INNER JOIN
PublisherTable ON PublisherTable.PublisherID = BookTable.PublisherID
LEFT OUTER JOIN
BookAuthorTable
INNER JOIN
AuthorTable ON AuthorTable.AuthorID = BookAuthorTable.AuthorID
ON BookTable.BookID = BookAuthorTable.BookID
WHERE
(BookTable.CategoryID = #CategoryID) OR
(PublisherTable.PublisherName LIKE N'%' + #PublisherName + N'%') OR
(BookTable.BookTitle LIKE N'%' + #BookTitle + N'%') OR
(AuthorTable.AuthorFName + ' ' + AuthorTable.AuthorLName LIKE N'%' + #AuthorName + N'%') OR
(CategoryTable.CategoryName LIKE N'%' + #CategoryName + N'%')
I want to search using a textbox and I use an ObjectDataSource with a GridView to show the results:
<asp:ObjectDataSource ID="ObjectDataSource5" runat="server"
DataObjectTypeName="BookDataBaseComponent.BookDetails"
DeleteMethod="DeleteBook" InsertMethod="InsertBook" SelectMethod="SearchBook"
TypeName="BookDataBaseComponent.BookDB" UpdateMethod="UpdateBook">
<DeleteParameters>
<asp:Parameter Name="BookID" Type="Int32" />
</DeleteParameters>
<SelectParameters>
<asp:Parameter DefaultValue="%" Name="CategoryID" Type="Int32" />
<asp:ControlParameter ControlID="booktb" DefaultValue="%" Name="BookTitle"
PropertyName="Text" Type="String" />
<asp:ControlParameter ControlID="DropDownList1" DefaultValue="%"
Name="CategoryName" PropertyName="SelectedValue" Type="String" />
<asp:ControlParameter ControlID="alntb" DefaultValue="%" Name="AuthorName"
PropertyName="Text" Type="String" />
<asp:ControlParameter ControlID="pubtb" DefaultValue="%" Name="PublisherName"
PropertyName="Text" Type="String" />
</SelectParameters>
</asp:ObjectDataSource>
When I run the project, I get an error message :
Input string was not in a correct format
how can <asp:Parameter DefaultValue="%" Name="CategoryID" Type="Int32" /> be valid? Default an int32 with %??
I've a a webform which update a db table, there is an error "Input string was not in a correct format" after submitted the form
nodeDetails.cs
protected void SqlDataSource_Updating(object sender, SqlDataSourceCommandEventArgs e)
{
DropDownList ddl = (DropDownList)(DetailsView1.Rows[0].FindControl("DropDownList4"));
DataRowView dr = (DataRowView)DetailsView1.DataItem;
e.Command.Parameters["#parent_id"].Value = ddl.SelectedValue;
}
some code in nodeDetails.aspx
UpdateCommand="UPDATE [node] SET [title] = #title, [parent_id] = #parent_id, [oid] = #oid, [display] = #display, [linkById] = #linkById, [showContent] = #showContent, [customLinks] = #customLinks, [contentType] = #contentType WHERE [id] = #id"
<UpdateParameters>
<asp:Parameter Name="title" Type="String" />
<asp:Parameter Name="parent_id" Type="Int32" />
<asp:Parameter Name="oid" Type="Int32" />
<asp:Parameter Name="display" Type="Byte" />
<asp:Parameter Name="linkById" Type="Byte" />
<asp:Parameter Name="showContent" Type="Byte" />
<asp:Parameter Name="customLinks" Type="String" />
<asp:Parameter Name="contentType" Type="String" />
<asp:Parameter Name="id" Type="Int32" />
</UpdateParameters>
The error will is caused by e.Command.Parameters["#parent_id"].Value = ddl.SelectedValue;
Anyone know what is the problem?
you need to make sure ddl.SelectedValue return correct integer value before setting parameter
DropDownList ddl = (DropDownList)(DetailsView1.Rows[0].FindControl("DropDownList4"));
int val;
if(int.TryParse(ddl.SelectedValue, out val)
{
e.Command.Parameters["#parent_id"].Value = val;
}
when you bind DropDownList4 make integer field as value member of it.
I am attempting to grab the recently inserted ID for a table, but I keep receiving a casting error. The item always contains NULL, and I am not sure why. I am following the instructions located here:
http://www.mikesdotnetting.com/Article/54/Getting-the-identity-of-the-most-recently-added-record
Here is my SqlDataSource:
<asp:SqlDataSource ID="SqlDataSource2" runat="server"
ConnectionString="<%$ ConnectionStrings:NH_SWAGConnectionString %>"
InsertCommand="INSERT INTO [tblOrders] ([OrderDate], [OrderTotal], [OrderAccount], [OrderCostCentre]) VALUES (#OrderDate, #OrderTotal, #OrderAccount, #OrderCostCentre); SET #OrderNewID = SCOPE_IDENTITY()"
SelectCommand="SELECT * FROM [tblOrders]"
UpdateCommand="UPDATE [tblOrders] SET [OrderDate] = #OrderDate, [OrderTotal] = #OrderTotal, [OrderAccount] = #OrderAccount, [OrderCostCentre] = #OrderCostCentre WHERE [OrderID] = #original_OrderID AND [OrderDate] = #original_OrderDate AND [OrderTotal] = #original_OrderTotal AND [OrderAccount] = #original_OrderAccount AND [OrderCostCentre] = #original_OrderCostCentre"
ConflictDetection="CompareAllValues"
OldValuesParameterFormatString="original_{0}"
OnInserting="SqlDataSource2_Inserting"
OnInserted="SqlDataSource2_Inserted">
<InsertParameters>
<asp:Parameter Direction="Output" Name="OrderNewId" Type="Int32" />
</InsertParameters>
<UpdateParameters>
<asp:Parameter Name="OrderDate" Type="DateTime" />
<asp:Parameter Name="OrderTotal" Type="Decimal" />
<asp:Parameter Name="OrderAccount" Type="String" />
<asp:Parameter Name="OrderCostCentre" Type="String" />
<asp:Parameter Name="original_OrderID" Type="Int32" />
<asp:Parameter Name="original_OrderDate" Type="DateTime" />
<asp:Parameter Name="original_OrderTotal" Type="Decimal" />
<asp:Parameter Name="original_OrderAccount" Type="String" />
<asp:Parameter Name="original_OrderCostCentre" Type="String" />
</UpdateParameters>
</asp:SqlDataSource>
Here is the code behind inserting the new record, and calling SCOPE_IDENTITY() to grab the new ID:
protected void btnOrder_Click(object sender, EventArgs e)
{
//Add entry to Order Table
SqlDataSource2.InsertParameters.Add("OrderDate", DateTime.Now.ToString("MMMM dd, yyyy"));
SqlDataSource2.InsertParameters.Add("OrderTotal", "0");
SqlDataSource2.InsertParameters.Add("OrderAccount", ItmUser);
SqlDataSource2.InsertParameters.Add("OrderCostCentre", ItmCostCode.Text);
SqlDataSource2.Insert();
}
protected void SqlDataSource2_Inserted(object sender, SqlDataSourceStatusEventArgs e)
{
OrderNewID = (int)e.Command.Parameters["#OrderNewId"].Value;
}
Why #OrderNewId above is NULL?
Ok I got it figured. Instead of using SET I used SELECT in the InsertQuery:
INSERT INTO [tblOrders] ([OrderDate], [OrderTotal], [OrderAccount], [OrderCostCentre]) VALUES (#OrderDate, #OrderTotal, #OrderAccount, #OrderCostCentre); SELECT #OrderNewID = SCOPE_IDENTITY()