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();
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 have 20 textboxes and a dropdownlist on my form.
I am using EditItemTemplate and a SqlDataSource for editing and inserting data.
I replaced a dropdownlist with a textbox and things didn't work. With the textbox, the form was working fine.
Initially, I had:
<asp:TextBox ID="IDTextBox" runat="server" Text='<%# Bind("EPMProjectUID") %>'/>
<asp:SqlDataSource ID="dsManageProject" runat="server"
SelectCommand="SELECT [EPMProjectUID] from Table"
UpdateCommand="UPDATE [Table] SET [EPMProjectUID] = #EPMProjectUID "
InsertCommand="Insert into [Table] values(EPMProjectUID)"
<SelectParameters>
<asp:Parameter Name="EPMScheduleUID" />
</SelectParameters>
<UpdateParameters>
<asp:Parameter Name="EPMScheduleUID" />
</UpdateParameters>
<InsertParameters>
<asp:Parameter Name="EPMScheduleUID" />
<InsertParameters>
</asp:SqlDataSource>
And the things were working,I use to get the data and update it and even store it.
But now, I want a dropdownlist here, so I added
<asp:DropDownList ID="UIDDropDownList" runat="server"></asp:DropDownList>
In the cs file, I wrote
DB db1 = new DB(Global.ConnStringName);
db1.QueryText = #"SELECT UID, ProjectName FROM Table ";
DataTable dt = db1.GetDataTable();
DropDownList ddlUID = (DropDownList)FormView1.FindControl("UIDDropDownList");
if (ddlUID != null)
{
ddlUID.DataSource = dt;
ddlUID.DataTextField = "ProjectName";
ddlUID.DataValueField = "UID";
ddlUID.DataBind();
}
And this helps me to load the data, but if I try to insert/update anything, it stores as null.
I have this two diferent classes to use in my ObjectDataSource:
"getColection" and "getLastColectionByUser"
This is my ObjectDataSource at aspx.
`
<asp:ObjectDataSource ID="ObjectDataSource1" runat="server" SelectMethod="getColection"TypeName="HepatiteNegocio.ViewProtocoloCol" SelectCountMethod="getColectionCount"
EnablePaging="True">
<SelectParameters>
<asp:Parameter Name="pWhere" Type="String" />
<asp:Parameter Name="pOrderBY" Type="String" />
<asp:Parameter Name="startRowIndex" Type="Int32" />
<asp:Parameter Name="maximumRows" Type="Int32" />
</SelectParameters>
</asp:ObjectDataSource>`
If radio button selected value is "all" select method is "getColection" else is "getLastColectionByUser", all right?
`if(radioButton.SelectedValue.Equals("all"))
{
ObjectDataSource1.SelectMethod = "getColection";
ObjectDataSource1.SelectCountMethod = "getColectionCount";
try
{
validation();
ObjectDataSource1.SelectParameters[0].DefaultValue = getWhere();
ObjectDataSource1.SelectParameters[1].DefaultValue = "protocolNumber";
}
catch
{
set an error message
}
}
else
{
ObjectDataSource1.SelectMethod = "getLastColectionByUser";
ObjectDataSource1.SelectCountMethod = "getLastCountColectionByUser";
try
{
validation();
ObjectDataSource1.SelectParameters[0].DefaultValue = getWhere();
ObjectDataSource1.SelectParameters[1].DefaultValue = "protocolNumber";
}
catch
{
set an erron message
}
}
ObjectDataSource1.DataBind();
GridView1.DataBind();`
When I debug it works fine. The SelectMethod and SelectCountMethod are changing BUT the gridView is still showing old values. The Classes are ok. What is going wrong?
You are probably changing the SelectMethod property after the ObjectDataSource is bound. Try adding ObjectDataSource1.DataBind(); at the end of the procedure you listed as a quick fix.
What event handler is the code running in?
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()
I am making a WebForm in asp.net and I want to display gridview with data from asp:SqlDataSource
My problem becomes when I try to skip (pass null) values for some of the Parameters.
Here is some snippets of my code
In aspx file sqldatasource looks like
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:ApplicationServices %>"
SelectCommand="art_bat_art" SelectCommandType="StoredProcedure">
<SelectParameters>
<asp:Parameter Name="art_naz" DefaultValue="HLA" ConvertEmptyStringToNull="true" Type="String" />
<asp:Parameter Name="art_sifra" DbType="String" Direction="Input"/>
<asp:Parameter Name="vrsta_id" DefaultValue="3" ConvertEmptyStringToNull="true" Type="Int32" />
<asp:Parameter Name="podvrsta_id" DefaultValue="13" ConvertEmptyStringToNull="true"
Type="Int32" />
<asp:Parameter Name="podgrupa2" DefaultValue="1365" ConvertEmptyStringToNull="true" Type="Int32" />
<asp:Parameter Name="podosobine" DefaultValue="1:9241" ConvertEmptyStringToNull="true"
Type="String" />
<asp:Parameter Name="podosobineOR" DefaultValue="true" ConvertEmptyStringToNull="true"
Type="Boolean" />
</SelectParameters>
My grid looks like this:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
DataKeyNames="id" DataSourceID="SqlDataSource1">
And troubles comes in code behind
One of parameters for my stored procedure is optional, If i pass it as null in SQL the stored procedure is
going to execute anyway.
I am trying to skip and pass that parameter as follows
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click1(object sender, EventArgs e)
{
SqlDataSource1.SelectParameters["art_sifra"].DefaultValue = DBNull.Value; //Cannot implicitly convert type
SqlDataSource1.SelectParameters["art_sifra"].DefaultValue = System.Data.SqlTypes.SqlString.Null; //Cannot implicitly convert type
SqlDataSource1.SelectParameters["art_sifra"].DefaultValue = System.Data.SqlTypes.SqlString.Null.ToString(); //IT compiles but i get NULL as text in SQL
//IF I Just skip seting of this parametar, My SqlDataSource won't call stored proce
SqlDataSource1.SelectParameters["art_sifra"].DefaultValue = string.Empty; //Again no execution of stored proce
//Even if I call SqlDataSource1.DataBind(); //nothing cames to sql
GridView1.DataBind();
}
}
You'll have to edit your SQL (or stored proc) to be able to handle an optional parameter.
ie: if you have:
SELECT blah FROM yourTable WHERE art_sifra = #art_sifra
change it to:
SELECT blah FROM yourTable WHERE (art_sifra = #art_sifra OR #art_sifra = '')
and then just change ConvertEmptyStringToNull="false" and set your select parameter to "":
SqlDataSource1.SelectParameters["art_sifra"].DefaultValue = "";
Also need to set CancelSelectOnNullParameter="false" on your datasource.
DBNull.Value; //Cannot implicitly convert type
Have you tried casting it? E.g.
DBNull.Value.Tostring()