Adding multiple update params sqldatasource - asp.net

This code is part of a SqlDataSource:
<UpdateParameters>
<asp:Parameter Name="username" Type="String" />
<asp:Parameter Name="first_name" Type="String" />
<asp:Parameter Name="surname" Type="String" />
</UpdateParameters>
How can i code this so i can add multiple parameters, since i can only seem to add one at a time. I do not wish to place these update params in my .aspx file since i wish to seperate my database related items.
SqlDataSourceUsers.UpdateParameters.Add(parameter);
Thanks.

You could place your params in a Dictionary (or list if using parameter objects) and then use a loop to add them...
var params = new Dictionary<string, string>
{
{"param1", "value1"},
{"param2", "value2"},
};
foreach(var param in params)
{
SqlDataSourceUsers.UpdateParameters.Add(
new SqlParameter(param.Key, param.Value)
);
}

Related

Procedure or function 'xyz' has too many arguments specified

I know this type of question has been asked at least a dozen times on SO, but I've gone through all the previous questions and answers I could find here and none that I have found apply. I am using several FormView objects on my page and now want to add the option to edit one of them. The FormView is populated by SqlDataSource linked to a stored procedure, so I made a stored procedure to update the records and added it to the SqlDataSource, which now looks like this:
<asp:SqlDataSource ID="TestSqlDataSource" runat="server"
SelectCommandType="StoredProcedure"
ConnectionString="<%$ ConnectionStrings:development %>"
SelectCommand="usp_GetNewTestDetails"
UpdateCommand="usp_UpdateTest"
UpdateCommandType="StoredProcedure"
onupdating="TestSqlDataSource_Updating">
<SelectParameters>
<asp:SessionParameter SessionField="TestID" Name="TestID"/>
</SelectParameters>
<UpdateParameters>
<asp:Parameter Name="testId" Type="Int32"/>
<asp:Parameter Name="testerLicense" Type="Int32" />
<asp:Parameter Name="premiseOwner" Type="String" />
<asp:Parameter Name="premiseAddress" Type="String" />
<asp:Parameter Name="premiseCity" Type="String" />
<asp:Parameter Name="premiseState" Type="String" />
<asp:Parameter Name="premiseZip" Type="String" />
<asp:Parameter Name="protectionType" Type="String" />
<asp:Parameter Name="testType" Type="String" />
<asp:Parameter Name="repairs" Type="String" />
<asp:Parameter Name="notes" Type="String" />
<asp:Parameter Name="testDate" Type="DateTime" />
<asp:Parameter Name="employerName" Type="String" />
<asp:Parameter Name="employerAddress" Type="String" />
<asp:Parameter Name="phoneNumber" Type="String" />
<asp:Parameter Name="emailAddress" Type="String" />
<asp:Parameter Name="dataEntryName" Type="String" />
<asp:Parameter Name="dataEntryPhone" Type="String" />
<asp:Parameter Name="signature" Type="String" />
<asp:Parameter Name="entryDate" Type="DateTime" />
</UpdateParameters>
</asp:SqlDataSource>
When I attempt to update a record, I'm getting an error that says there are too many parameters in my query. I have triple checked that the parameters in my code match exactly (name, number, and even order) to the ones in my stored procedure.
In attempting to find answers, I came across this post which referenced this site (had to go to archive.org because the original appears to be down). I applied what they suggested for adding the parameters to the trace function. What I found was that in my stored procedure, there are a few "lookup" values from the select procedure that aren't in the update procedure. The table I'm trying to update only has the ID of the tester, but the users would like to see their name as well, so it references that table, but in the FormView those fields are read-only during edit mode so they can't attempt to change it. All the other parameters line up... only those lookup values are off.
I thought that by including the specific list of parameters to pass that it would only use those parameters, but that appears to be incorrect. Now I'm stumped because I have already specified the parameters, and I can't see anywhere that they are being overwritten with the ones from the select stored procedure. Where do I tell it not to use those read-only values?
I don't want to remove them from the original stored procedure because they will be needed by the users. The one workaround that I have come up with so far is to add them to the stored procedure and then just never use them. Although I'm fairly certain this would work, it is very much just covering up the problem rather than fixing it.
EDIT: Additional code, per request
This is the method that outputs the parameters to the trace function:
protected void TestSqlDataSource_Updating(object sender, SqlDataSourceCommandEventArgs e)
{
for (int i = 0; i < e.Command.Parameters.Count; i++)
{
Trace.Write(e.Command.Parameters[i].ParameterName);
if (e.Command.Parameters[i].Value != null)
{
Trace.Write(e.Command.Parameters[i].Value.ToString());
}
}
}
This is the stored procedure used for updating:
ALTER PROCEDURE [dbo].[usp_UpdateTest]
#testId INT ,
#testerLicense INT ,
#premiseOwner VARCHAR(50) ,
#premiseAddress VARCHAR(150) ,
#premiseCity VARCHAR(50) ,
#premiseState VARCHAR(2) ,
#premiseZip VARCHAR(10) ,
#protectionType VARCHAR(11) ,
#testType VARCHAR(2) ,
#repairs VARCHAR(200) ,
#notes VARCHAR(300) ,
#testDate DATETIME ,
#employerName VARCHAR(50) ,
#employerAddress VARCHAR(150) ,
#phoneNumber VARCHAR(25) ,
#emailAddress VARCHAR(60) ,
#dataEntryName VARCHAR(50) ,
#dataEntryPhone VARCHAR(25) ,
#signature VARCHAR(50) ,
#entryDate DATETIME
AS
BEGIN
SET NOCOUNT ON;
UPDATE dbo.Tests
SET TesterLicense = #testerLicense ,
PremiseOwner = #premiseOwner ,
PremiseAddress = #premiseAddress ,
PremiseCity = #premiseCity ,
PremiseState = #premiseState ,
PremiseZip = #premiseZip ,
ProtectionType = #protectionType ,
TestType = #testType ,
Repairs = #repairs ,
Notes = #notes ,
TestDate = #testDate ,
EmployerName = #employerName ,
EmployerAddress = #employerAddress ,
PhoneNumber = #phoneNumber ,
EmailAddress = #emailAddress ,
DataEntryName = #dataEntryName ,
DataEntryPhone = #dataEntryPhone ,
Signature = #signature ,
EntryDate = #entryDate
WHERE TestID = #testId
END
Ended up figuring this out on my own. It was related to the fact that Visual Studio created the templates for me based on the stored procedure's schema. When the templates are autogenerated, every textbox in the <EditItemTemplate> section gets generated like this:
<asp:TextBox ID="TestIDTextBox" runat="server" Text='<%# Bind("TestID") %>'/>
Turns out that it is the Bind statement that caused this. VS automatically creates a parameter for any field populated using Bind. Although I was led to believe that the <UpdateParameters> section should have overridden this, it was actually the other way around. I was able to prevent these few read-only fields from passing back their parameters by changing the code on those fields from Bind to Eval:
<asp:TextBox ID="TestIDTextBox" runat="server" Text='<%# Eval("TestID") %>'/>
Works perfectly now.
Addendum:
Found that this causes the same problem in the other direction as well. If you mark a field you don't want edited as Eval but it needs to be included in the update (such as a row ID) it will not work, this time for too few parameters. I'm wondering now what the purpose of the <UpdateParameters> section even is, since it doesn't seem to follow anything in there...
You can delete unwanted parameters during e.g OnDeleting event (e.Command.Parameters.RemoveAt(i)).

ASP.NET UpdateCommand with multiple tables updates

I am using ASP.NET and using a grid with the UpdateCommand to update 2 tables
I have the following but doesn't seem to work as I do not get any errors but it simply does not update. From what you can see, am I on the right track?
UpdateCommand="UPDATE [tbl_ProgDt] SET [Type] = #type, [Identifiction] = #samplePoint WHERE [Seq] = #valID UPDATE [tbl_Prog] SET StoreNum = #storeNum WHERE ID = (SELECT ID FROM [tbl_ProgDt] WHERE [Seq] = #valID " >
<UpdateParameters>
<asp:Parameter Name="type" Type="String" />
<asp:Parameter Name="samplePoint" Type="String" />
<asp:Parameter Name="valID" Type="Int32" />
<asp:Parameter Name="storeNum" Type="Int32" />
<asp:Parameter Name="valID" Type="Int32" />
</UpdateParameters>
If you need to do something like that, it would be better to create a stored procedure and wrap the two update sentences using a database transaction
You need to specify:
UpdateCommandType="StoredProcedure" UpdateCommand="Stored Procedure Name"
In your Stored Procedure, something like this:
BEGIN TRANSACTION;
-- your update sentences
COMMIT TRANSACTION;

Gridview not updating table when column/cell starts with no data

UPDATED: Here is the SP, it doesn't match exactly because of ongoing testing, but you get the jist. Some fields are commented out because of testing....
#tableName Varchar(150),
#new_lang_String nvarchar(max),
-- #lang_String nvarchar(max),
#ID int,
#prev_LangString nvarchar(max) = NULL,
#original_lang_String nvarchar(max) = NULL,
#brief_Descrip nvarchar(max) = NULL,
#submittedBy nvarchar(250) = NULL
AS
/* SET NOCOUNT ON */
DECLARE #lang_String varchar(max);
SET #prev_LangString = #new_lang_String;
DECLARE #submitDate1 DATETIME;
SET #submitDate1 = GETDATE();
DECLARE #sql varchar(max);
SET #lang_String = #original_lang_String;
BEGIN
SET #sql = 'UPDATE ' + #tableName + ' SET [lang_String] = ''' + COALESCE(#lang_String, NULL) + ''', [date_Changed] = ''' + convert(varchar(20), #submitDate1) + ''', [prev_LangString] = ''' + COALESCE(#prev_LangString, NULL) + ''', [brief_Descrip] = ''' + COALESCE(#brief_Descrip, NULL) + ''', [submittedBy] = ''' + #submittedBy + '''
WHERE (ID = ' + CAST(#ID as nvarchar(10)) + '); '
EXECUTE(#sql);
END
RETURN
As you can probably tell in the code I have been struggling with handling the Null in some of the fields as well. Hence the default values inteh update parameters of = " " on some fields.
I am using a gridview to display information that is retrieved from a table in a SQL Express DB. When the user clicks EDIT, and enters information, I am trying to update the table with a STORED PROCEDURE called from the Gridview. See aspx code below.
The issue is that the column which is being edited will not update the DB table unless it had previously had data stored in it, as in the cell in the column IS NOT Null. No errors.
Since most cells in this column are Null to begin with, no data is getting updated. No errors, just nothing written to the table. If the table previously had data within the column cell in question it can be succesfully edited and updated.
Gridview from ASPX Page....
<asp:BoundField DataField="lang_String" HeaderText="Foreign Text" SortExpression="lang_String">
<ControlStyle Width="400px"/>
</asp:BoundField>
Update Command on Gridview calls SP, which works, provided column/cell already had data...
UpdateCommand="EXEC usp_UpdatePTEdit #tableName, #lang_String=#lang_String, #ID=#original_ID, #prev_LangString=#original_lang_String, #brief_Descrip=#brief_Descrip, #submittedBy=#SubmittedBy">
Parameters passed to UpdateCommand, only using a few...
<UpdateParameters>
<asp:SessionParameter Name="tableName" SessionField="tableName1" />
<asp:SessionParameter Name="submittedBy" SessionField="SubmittedByUser" />
<asp:Parameter Name="data_text" Type="String" />
<asp:Parameter Name="lang_String" Type="String" DefaultValue=" " />
<asp:Parameter Name="date_Changed" Type="DateTime" />
<asp:Parameter Name="prev_LangString" Type="String" DefaultValue=" " />
<asp:Parameter Name="needsTranslation" Type="String" />
<asp:Parameter Name="displayRecord" Type="String" />
<asp:Parameter Name="brief_Descrip" Type="String" DefaultValue=" " />
<asp:Parameter Name="original_ID" Type="Int32" />
<asp:Parameter Name="original_data_text" Type="String" />
<asp:Parameter Name="original_lang_String" Type="String" />
<asp:Parameter Name="original_date_Changed" Type="DateTime" />
<asp:Parameter Name="original_prev_LangString" Type="String" />
<asp:Parameter Name="original_needsTranslation" Type="String" />
<asp:Parameter Name="original_displayRecord" Type="String" />
<asp:Parameter Name="original_brief_Descrip" Type="String" />
<asp:Parameter Name="original_submittedBy" Type="String" />
</UpdateParameters>
Everything works if the cell originally has data, "original_lang_String" but if it has not been populated, I can not use the Edit operation of the Gridview to successfully update the table.
Any help or suggestions would be appreciated.
#prev_LangString=#original_lang_String
Depending on what is in usp_UpdatePTEdit, I bet it's failing because somewhere it's checking for an original value that doesn't exist. NULL is special and equality checks for it fail.
Post the code that is in usp_UpdatePTEdit stored proc for more help.
I think the problem may be with the assignment of the parameters to the column of the same name (#lang_String=#lang_String). I recommend specifying the parameters in the order that they appear in the stored proc and remove the #name= syntax. I think that is just going to get the datasource or grid view confused.
Update
I think that you would be better off changing the UpdateCommand to:
UpdateCommand="usp_UpdatePTEdit"
and adding:
UpdateCommandType="StoredProcedure"
This seems to be a better fit for how the update command is designed to work.

setting the default value for insert parameters in sql datasource asp.net

i have a datasource, which has an insertparameters, one of which whose type is set to Boolean, but while adding it from code behind insertparameters.defaultvalue always return string.
code behind code:
if (e.CommandName == "InsertNew")
{
TextBox Title = GridView1.FooterRow.FindControl("txtAddTitle") as TextBox;
TextBox Quote = GridView1.FooterRow.FindControl("txtAddQuote") as TextBox;
TextBox QuoteLink = GridView1.FooterRow.FindControl("txtAddQuoteLink") as TextBox;
CheckBox Published = GridView1.FooterRow.FindControl("chkAddBox") as CheckBox;
TextBox PublishedDate = GridView1.FooterRow.FindControl("txtAddPublishedDate") as TextBox;
SqlDataSource1.InsertParameters["Title"].DefaultValue = Title.Text;
SqlDataSource1.InsertParameters["Quote"].DefaultValue = Quote.Text;
SqlDataSource1.InsertParameters["QuoteLink"].DefaultValue = QuoteLink.Text;
SqlDataSource1.InsertParameters["Published"].DefaultValue = Convert.ToString(Published.Checked);
SqlDataSource1.InsertParameters["PublishedDate"].DefaultValue = PublishedDate.Text;
SqlDataSource1.Insert();
}
and aspx code for sql datasource is:
<InsertParameters>
<asp:Parameter Name="Title" Type="String" />
<asp:Parameter Name="Quote" Type="String" />
<asp:Parameter Name="QuoteLink" Type="String" />
<asp:Parameter Name="Published" Type="Boolean" />
<asp:Parameter Name="PublishedDate" Type="DateTime" />
</InsertParameters>
Please reply how should i set the datatype as boolean from code behind.
1: Not sure why you are setting DefaultValue instead of the value
Or
2: Can you try this:
SqlDataSource1.InsertParameters["Published"].DefaultValue = Published.Checked==true?"true":"false";

ObjectDataSource Update/Delete parameters from GridView

<asp:ObjectDataSource ID="MMBRSODS" runat="server"
OldValuesParameterFormatString="original_{0}"
TypeName="Flow_WEB_Nemerle.SQLModule"
SelectMethod="GetMembers"
UpdateMethod="UpdateMember"
DeleteMethod="DeleteMember">
<UpdateParameters>
<asp:Parameter Name="UserName" Type="String" />
</UpdateParameters>
<DeleteParameters>
<asp:Parameter Name="UserName" Type="String" />
</DeleteParameters>
</asp:ObjectDataSource>
Select method returns array of strings . But How I need to appear selected node for edit delete methods get this string (userName) ?
for methods like :
[DataObjectMethod(DataObjectMethodType.Delete, true)]
static public DeleteMember(...
What are you binding the original list against? Let's say you are binding a list; you can always do the following to do that type of operation:
MMBRSODS.UpdateParameters["UserName"].DefaultValue = list.SelectedValue;
MMBRSODS.Update();
So supplying the default value allows you to still use the update, the param relies on this default and supplies it to the backend... what control are you using to show the data?
HTH.

Resources