Sending parameter to code behind from stored procedure - asp.net

I'm using a FormView and binding it to a SqlDataSource using a stored procedure to edit a record. The thing is that after updating the record I need to call another function, which I'm doing using the onClick attribute of the button.
This function has to insert a few records into another table, using the ID of the record edited in the FormView. I know how to use SCOPE_IDENTITY when in the same stored procedure, but this time I need some logic that is easier to accomplish in the code-behind, but I don't know how to obtain the ID, so any leads would be great.
Here is the button:
<asp:Button ID="EditButton" runat="server" CausesValidation="True" CommandName="Update"
Text="Edit" OnClick="setProcessProgress" />
And here is a stripped down version of the code behind:
protected void setProcessProgress(object sender, EventArgs e)
{
int ID_p;
ID_p = ; //TODO: Here I need to obtain the ID of the last edited record from the EditButton
setProgress(ID_p);
}
The stored procedure is a simple UPDATE statement.
I'm thinking of passing a parameter to the code behind, but not sure how to, perhaps something like this OnClick="setProcessProgress(#id)"

try like this, and you need to attach OnCommand="CommandEventHandler" event handler to your button . check for More Info Button.Command
<asp:Button ID="EditButton" runat="server" CausesValidation="True" CommandName="Update"
Text="Edit"
CommandArgument="1"
OnCommand="CommandBtn_Click" />
and the code for to get the ID
protected void CommandBtn_Click(Object sender, CommandEventArgs e)
{ if (e.CommandName == "Update")
{
yourID =Convert.ToInt32(e.CommandArgument);
}
}

You can use out parameter for update store procedure. This will give you the ID after
update.
Then you can use the ID for your insert.
http://blogs.msdn.com/b/spike/archive/2009/05/07/a-simple-example-on-how-to-get-return-and-out-parameter-values-using-ado-net.aspx

Related

Duplicate PK Check on saving - Alert not firing

I'm trying to check for duplicate pks when trying to insert a new record. I want to show an error if it does, but i'm not sure where i am going wrong/if this is the right way to go.
Please see below. I put a breakpoint at the function AgentSave_Click and saw its its not going into the IF statement
<asp:Button ID="AgentSave" runat="server" CausesValidation="true" OnClick="AgentSave_Click" Style="margin-left: 0px" Text="Save" />
protected void AgentSave_Click(object sender, EventArgs e)
{
try
{
if (AccountNumber.Text.Trim().Equals("select PRIMARYKEYNAME from TABLEXYZ"))
{
Response.Write("<script type=\"text/javascript\">" + "window.alert('ERROR: The Account Number entered is already assigned to an Agent.');" + "</script>");
AccountNumber.Focus();
}
else
{.....
OnClientClick property is meant to execute some javascript code on client before data is send back to server.
According your answer you are trying to execute server code. So you should replace onclientclick with onclick="duplicate_PK" which gets executed on server.
Regards,
Uros
<asp:Button ID="AgentSave" runat="server" OnClick="AgentSave_Click" Style="margin-left: 0px" Text="Save" />
remove CausesValidation="true" or chANGE TO CausesValidation="false"

how get value of aspxcombobox in code behind

I have aspxcombobox(Devexpress)
asp.net :
<dx:ASPxComboBox ID="ASPxComboBox1" runat="server" DataSourceID="SqlDataSource1">
<Columns>
<dx:ListBoxColumn FieldName="cg_id" />
<dx:ListBoxColumn FieldName="cg_name" />
</Columns>
</dx:ASPxComboBox>
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:TravelConnectionString %>" SelectCommand="SELECT * FROM [Categorys_Group]"></asp:SqlDataSource>
Code behind:
protected void Button1_Click(object sender, EventArgs e)
{
Response.Redirect("Accounting/Check.aspx?id=" + ASPxComboBox1.SelectedItem.GetValue("cg_name"));
}
When click button. i want to get value index selected of aspxcombobox.
I try get value of combobox, but it only return value first ( = 0 ).
WHo can help me? get value of aspxcombobox.
This problem may be caused by wrong selectedItem or selectedIndex property or when aspxcombobox is empty etc.
MessageBox.show(ASPxComboBox1.Value != null? ASPxComboBox1.Value.ToString():string.Empty);
To skip from this error you should know ValueType property properly.
And also see it..
ASPxClientComboBox_GetSelectedItem
You have 2 choices:
on the code behind, create a switch case on the index selected, and bindes the data to comboBox accordingly.
on the data level: in your data base access layer, using your Data Provider class that fetches data from your database, you have to create a GET method that takes the SELECTED INDEX as a parameter, pass that SELECTED INDEX to a pre-defined STORED PROCEDURE and do a SELECT according to the choosen index.
I would suggest using the second solution for the following reasons:
no changes made on the code behind side.
fetch is done on the database level according to the selected index, which assures the correct data imported. --> Your Data Source is Bound earlier in the process.
small changes are made on the STORED PROCEDURE :)
Best Regards,
ANDOURA

Two Buttons updating one item of a listview

I have two buttons in a ListView. With a click on the first Button I want to update the ListView-Item. With a click on the second button i want to update the ListView-Item and redirect to a different page. Both Buttons have a property CommandName="Update". I wanted to solve my problem with the CommandArgument-Property and the OnItemUpdated-Event, but I do not know how to get the value of this Property in the event.
<asp:ObjectDataSource ID="ods" runat="server" SelectMethod="Select" UpdateMethod="Update">
<SelectParameters>
<asp:Parameter ..... />
</SelectParameters>
<UpdateParameters>
<asp:Parameters .... />
</UpdateParameters>
</asp:ObjectDataSource>
<asp:ListView ID="lv" runat="server" DataSourceID="ods" DataKeyNames="ID" OnItemUpdated="lv_OnItemUpdated">
<ItemTemplate>...</ItemTemplate>
<EditItemTemplate>
<asp:Button ID="btnUpdate" runat="server" CommandName="Update"/>
<asp:Button ID="btnUpdate2" runat="server" CommandName="Update"/>
</EditItemTemplate>
</asp:ListView>
And in codebehind:
protected void lv_OnItemUpdated(object sender, ListViewUpdateEventArgs e)
{
...
}
Is it possible to decide in lv_OnItemUpdated which Button the user clicked?
I don't believe there is a way to distinguish which control issued the Update command, since sender is the ListView itself.
A workaround would be for you to give one button the CommandName "Update", and the other "UpdateRedirect".
The "UpdateRedirect" button will fire the ListView_ItemCommand event, and from there you can call ListView.UpdateItem, keeping your updating logic in there, and then redirect next.
Why do you insist on using the OnItemUpdated event?
Well there are 2 to 3 ways of doing it: One is of CommandArgument as:
<asp:Button id="Button1"
Text="Sort Ascending"
CommandName="Sort"
CommandArgument="Ascending"
OnCommand="CommandBtn_Click"
runat="server"/>
<asp:Button id="Button2"
Text="Sort Descending"
CommandName="Sort"
CommandArgument="Descending"
OnCommand="CommandBtn_Click"
runat="server"/>
and than on server side you can have:
void CommandBtn_Click(Object sender, CommandEventArgs e)
{
if(e.CommandName == "Sort")
//do you work and so on
}
or you can cast the sender as button and take it ID to see, which button was it:
((Button)sender)).ID
or you can get button ID as:
String ButtonID = Request["__EVENTTARGET"];
I hope it will help you in fixing your problem.
so you can have like:
protected void lv_OnItemUpdated(object sender, ListViewUpdateEventArgs e)
{
// either use e.CommandName
// or user ((Button)sender)).ID
}
Give each button a distinct name. Have the same event handling method in your code behind handle both button click events. Then check which button called the method.
EDIT: A workaround would be to use javascript to put the name of the clicked button into a hidden field on the form BEFORE it goes server side (using a client side script). Then in your Listview you could check the value of the hidden field to see which button was clicked.
Ok, yes, the itemcommand is what you want:
The lifecycle for an update or insert triggers both their native events AND the itemcommand event. The itemCommand event will occur prior to the itemUpdating or the itemInserting events.
So, you can create a boolean variable called called "bSecondButtonClicked" for example Add the command argument to both buttons with the Commandname='UPDATE". the e.command argument can be evaluated at the itemcommand event point. There set your Boolean variable (or however you implement it) to true. Then, at the itemupdating event, trigger your code based on the bSecondButtonClicked.
You need to get into the ItemCommand event of your ListView
protected void lstvw_ItemCommand(object sender, ListViewCommandEventArgs e)
{
switch (e.CommandName)
{
case "new":
try
{
//e.CommandArgument
//e.CommandSource
// do your stuff here
}
catch (Exception ex)
{
}
break;
default:
break;
}
}

How to hide link button based on a result returned by a class ?

I am bit new to C# and got a question.
I have a class as below that simply return false ( this is just to test)
public class SetAuthority
{
public SetAuthority()
{
//
// TODO: Add constructor logic here
//
}
public static Boolean AuthorizedToAddEdit()
{
return false;
}
}
I have a DetailsView with two link buttons to Edit and add New record. I want to hide the link buttons based on the above class method returning value.
<ItemTemplate>
<asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="False" visible='<%# SetAuthority.AuthorizedToAddEdit() %>'
CommandName="Edit" Text="Edit"></asp:LinkButton>
<asp:LinkButton ID="LinkButton2" runat="server" CausesValidation="False" visible='<%# SetAuthority.AuthorizedToAddEdit() %>'
CommandName="New" Text="New"></asp:LinkButton>
</ItemTemplate>
Above works file and Edit and New link buttons are hidden when I run the program.
But the question is, I have a separate link button outside of the DetailsView. It is just a link to navigate to another page. I want to hide this in similar way using the same logic. I have the below code in my webform.
<asp:LinkButton ID="LinkButton5" runat="server" CausesValidation="False" visible='<%# SetAuthority.AuthorizedToAddEdit() %>'
CommandName="OpenAdminPage" Text="Open Admin Page"></asp:LinkButton>
But the link button is always visible and seems it is not calling the class and not getting the value back. It appeared to be the class not return any value and can someone help me to identify what is the different between having this and working in DetailsView and not working for a simple link button.
Note: have a workaround where I can call the same method in Page Load event that works fine without any issue. Code is below
protected void Page_Load(object sender, EventArgs e)
{
Boolean myAllowAdd;
myAllowAdd = SetAuthority.AuthorizedToAddEdit();
if (myAllowAdd == false)
{
LinkButton1.Visible = false;
}
}
The reason is that this is for databinding expressions only: <%# Since the DetailsView is databound it works there.
If you would DataBind the page it worked also for the LinkButton outside of the DetailsView:
protected void Page_Load(object sender, EventArgs e)
{
Page.DataBind();
}
inline asp.net tags... sorting them all out (<%$, <%=, <%, <%#, etc.)
Side-note: be careful with static in ASP.NET. The static method does not yet hurt. But if you'd also use static fields you'd enter a minefield since it would be shared across all requests. Your current code-behind "work-around" is the better approach anyway.

How to call server side code on textbox key enter in ASP.NET

How do I call server side code for textbox's in asp.net when user presses enter key? Code behnid method is creating a dynamic control based upon a LINQ query from data table.
The textbox has a TextChanged event that will fire when the focus leaves the textbox. If this isn't good enough for you, your going to need to use javascript and the onkeypress event.
As there's no description of what your doing after the event, I'm not sure what to offer as sample code.
In my opinion OP want to submit data with pressing enter in the textbox, then do sth with string from textbox.
So if I understand it right here is solution to do this:
//aspx
<asp:Panel ID="pnlSubmit" runat="server" DefaultButton="btnSubmit">
<asp:TextBox runat="server" ID = "txbText"></asp:TextBox>
<asp:Button ID="btnSubmit" runat="server" Text="Submit" OnClick="btnSubmit_Click" />
</asp:Panel>
//aspx.cs
protected void btnSubmit_Click(object sender, EventArgs e)
{
string textFromTextBox = txbText.Text;
//do sth with that string
}

Resources