Using ASP.NET/C#/nHibernate architecture - I have a GridView with an ObjectDataSource and am having problems getting the delete method to work.
When I simply use the Remove(T entity) function declared in my service layer (which then calls down to my nHibernate repository), the GridView_RowDeleting() method gets called, followed by ObjectDataSource_Deleting(), and then the service layer function is invoked and the business object is properly deleted.
However, when I try to use the RemoveByID(int ID) function, after the GridView_RowDeleting() and ObjectDataSource_Deleting() methods are called, the service layer is never being invoked.
I think this has something to do with the ObjectDataSource.DeleteParameters, but I can't seem to get it right.
Below is the code snippet for the GridView and ObjectDataSource. As you can see, I have the business object's primary key pkChapter7ID listed in the GridView's DataKeyNames:
<asp:GridView ID="gvChapter7" runat="server" DataSourceID="odsChapter7" DataKeyNames="pkChapter7ID">
<Columns>
<asp:BoundField DataField="pkChapter7ID" HeaderText="pkChapter7ID" SortExpression="pkChapter7ID"/>
...
</Columns>
</asp:GridView>
<asp:ObjectDataSource ID="odsChapter7" runat="server"
DeleteMethod="RemoveByID" OldValuesParameterFormatString="original_{0}"
SelectMethod="FindAllForProjectID" TypeName="CLS.Services.Chapter7Service">
<DeleteParameters>
<asp:Parameter Name="ID" Type="Int32" />
</DeleteParameters>
<SelectParameters>
<asp:SessionParameter Name="ID" SessionField="ProjectID" Type="Int32" />
</SelectParameters>
</asp:ObjectDataSource>
And the relevant portion of my generic service layer (calls down the nHibernate repository, which is working fine once I get there):
[DataObjectMethod(DataObjectMethodType.Delete, false)]
public virtual void Remove(T entity)
{
_repository.Remove(entity);
}
[DataObjectMethod(DataObjectMethodType.Delete, true)]
public virtual void RemoveByID(int ID)
{
T entity = FindBy(ID);
if (entity != null)
_repository.Remove(entity);
}
I have tried setting DeleteParameters in the _RowDeleting method:
protected void gvChapter7_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
odsChapter7.DeleteParameters["ID"].DefaultValue = e.Keys["pkChapter7ID"].ToString();
}
As well as numerous ways of setting up the ObjectDataSource control parameter in the aspx page, such as:
<DeleteParameters>
<asp:ControlParameter ControlID="gvChapter7" Name="ID" PropertyName="SelectedDataKey" Type="Int32" />
</DeleteParameters>
Can anyone see what I am missing?
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. :(
<asp:LinqDataSource ID="LinqDataSource2" runat="server" ContextTypeName="DataClassesDataContext"
TableName="PrivateMessages" Where="Sender == #Sender">
<WhereParameters>
<asp:QueryStringParameter Name="Sender" QueryStringField="idCompany" Type="String" />
</WhereParameters>
</asp:LinqDataSource>:LinqDataSource>
this code select from table PrivateMessages where Sender==QueryString('idCompany')
this code work fine.
i want select from privateMessage where Sender=="admin"????????
where sender equal a const string.
You can use Selecting event and do like..
protected void LinqDataSource1_Selecting(object sender, LinqDataSourceSelectEventArgs e)
{
e.WhereParameters["Sender"] = set here...
}
Or you can replace the WhereParameters section with something like
<WhereParameters>
<asp:Parameter Name="Sender" Type="String" DefaultValue="admin" />
</WhereParameters>
Depends on you in choosing what flavor of this 2 solutions best suits this scenario.
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 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()
I'm using an ObjectDataSource to sort/page/filter as below:
<asp:ObjectDataSource
ID="odsCompaniesIndex" runat="server" EnablePaging="true"
SelectMethod="GetCompaniesSubset"
StartRowIndexParameterName="startRowIndex"
MaximumRowsParameterName="maximumRows"
SelectCountMethod="GetCompaniesCount"
SortParameterName="sortExpression"
TypeName="Company">
<SelectParameters>
<asp:ControlParameter ControlID="ddlStatus"
ConvertEmptyStringToNull="true"
DbType="Boolean" PropertyName="SelectedValue" Name="status" />
</SelectParameters>
</asp:ObjectDataSource>
The gridview consuming the ObjectDataSource:
<asp:GridView ID="gvCompanyIndex" AutoGenerateColumns="true" runat="server" DataSourceID="odsCompaniesIndex"
AllowPaging="true" DataKeyNames="company_id" AllowSorting="true">
</asp:GridView>
I want to pass in a number of parameters like the one above into SelectParameters. The method call 'GetCompaniesSubset' executes but on the return I get the following error:
ObjectDataSource 'odsCompaniesIndex'
could not find a non-generic method
'GetCompaniesCount' that has
parameters: status.
My SelectMethod is:
public DataSet GetCompaniesSubset(
int startRowIndex, int maximumRows, string sortExpression, bool status)
{...}
How do you allow the SelectMethod to utilise StartRowIndexParameterName/MaximumRowsParameterName and any extra parameters?
Thanks
The problem is that GetCompaniesCount does not have status parameter, not GetCompaniesSubset.