how to pass a parameter by pressing a button - c#

i have the situation: i'm showing many lines from the DB on the page. just creating dynamic lines (<% foreach (res in DBVar) %>). Every line has a button. every button use just 1 OnClick method. I really dont care of the name(value) of these buttons, but i can't take, how can i pass a parameter (e.g. a ID of a line from DB (res.ID)) from the .aspx page to OnClick Method. (Using LINQ to SQL)
I tried to take my param to the name(value) of a button with "<input type="button" value="<%= "string"+DBVar.ID%>" and so on. the runat=server even can't take the variable on the name(value) coz of this i used just input method.

Use OnCommand event and assign CommandArgument
<asp:Button ID="Button1" runat="server" Text="Submit" CommandArgument='<%= res.ID %>' OnCommand="Button1_Click" />
in code behind
protected void Button1_Click(Object sender, CommandEventArgs e)
{
string ID=e.CommandArgument.ToString();
}

Set the CommandName and CommandArgument of the buttons during the bind and read them back out on your onclick event.
http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.button.commandname.aspx
http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.button.commandargument.aspx

check this link
passing dynamic values for each row in listview
he has done same thing and it also shows how to access the values in code behind

Related

Add asp.net LinkButton to a Literal using c#

I want to add some asp.net linkbutton controls to a literal on a c# web form application like code below:
StringBuilder sb = new StringBuilder("<ul>");
sb.Append("<li>");
sb.AppendFormat("<asp:LinkButton runat='server' class='add-row' ID='BtnAdd' OnClick='BtnAdd_Click' CommandArgument='test'>{0}</asp:LinkButton>", "Text on the link");
sb.Append("</li></ul>");
this.Literal.Text = sb.ToString();`
and also i want to fire event of click and get CommandArgument's value of that.
private void BtnAdd_Click(object sender, EventArgs e)
{
//get the value of CommandArgument
}
I tried these and the linkbutton added to the literal successfully. but the linkbutton didn't convert to <a> tag and i found that with the firebug like this and no any events couldn't fire:
I want make a tree with leafs as linkbuttons using <ul><li> tags overall.
It would be very helpful if someone could explain solution for this problem.
The correct approach here is via the WebControl api and not from the template.
Your approach may work for HTML content only.
What you need to do is handle a page lifecycle event like OnInit, get a reference to your container control (this.MyPanel), and dynamically add items to that control's children property (this.MyPanel.Children.Add(new....))
The suggested Repeater solution is not suited for tree structure data sources, works for a list though...
As suggested by Andrei using linkbuttons in this way will not work.
I have used a similar solution in the past by creating a query parameter for each a tag in the literal and redirecting to either the current page or a different page and extracting the query parameter from there.
I would however advise you to first try and see if there is not a different way to accomplish what you are trying to do as the literal solution ends up very cluttered and code heavy.
I think a Repeater would better suit your purpose.
<ul>
<asp:Repeater ID="Repeater1" runat="server">
<ItemTemplate>
<li><asp:LinkButton ID="BtnAdd" runat="server" CssClass="add-row" OnClick="BtnAdd_Click">Text on the link</asp:LinkButton></li>
</ItemTemplate>
</asp:Repeater>
</ul>
And if you want to use CommandArgument you need an OnCommand, not a OnClick
<asp:LinkButton ID="BtnAdd" runat="server" CssClass="add-row" OnCommand="BtnAdd_Command" CommandArgument='<%# Eval("value") %>'>
protected void BtnAdd_Command(object sender, CommandEventArgs e)
{
string commandArgument = e.CommandArgument.ToString();
}
If you have single <asp:LinkButton ..> then you can set it's property at run time. Like
BtnAdd.Id="";
or if you multiple then you can use AddControl method below is link
How to add controls dynamically when click button in asp.net?
How to add controls dynamically to ASP.NET form?
If you have to use asp: LinkButton just for one time then do it in this way.
<asp:Literal runat="server" ID="DocLink"></asp:Literal>
<asp:LinkButton runat="server" ID="LinkButton1" OnCommand='LinkButton1_Click'></asp:LinkButton>
and in .cs file
LinkButton1.Text = CurrentListItemAbsoluteUrl;
LinkButton1.CommandArgument = CurrentListItemAbsoluteUrl;
public void LinkButton1_Click(Object sender, CommandEventArgs e)
{
e. CommandEventArgs //To get your parameter

Bind a textbox value in a label box using c# inside a uframe

I have entered a value in text box and click the button the value should bind in a label.
The code must be in c# not in query. There is no database also.how please say the code behind in c#. It is button click event. while click the button the page should post back and bind the data how to bind a textbox value in a label box using c#. The value must bind in postback method.
easy , take a look at the below code:
<asp:TextBox Id="txt1" runat="server" />
<asp:button Id="btn1" runat="server" onClick="Button1_Click"/>
<asp:Label Id="lbl1" runat="server"/>
//in the code behind implement the Button1_Click
protected void Button1_Click (object sender, EventArgs e)
{
lbl1.Text= txt1.Text;
}
It as easy as the following:
LabelID.Text = TextBoxID.Text;
Where LabelID is the ID of your Label control and TextBoxID is the ID of your TextBox control.
You should place this code inside the button click's event.
Update
Please use for your purpose ASP.NET Web Server Controls.
<asp:TextBox ID="textBoxId" runat="server"/>
<asp:Label ID="labelId" runat="server"/>
Then you can access the values of Text property of both the above controls, like above:
labelId.Text = textBoxId.Text;

How to check whether ASP.NET button is clicked or not on page load

How can I check whether a particular button was clicked or not in ASP.NET?
I think I need to perform some operation on Page_Load. This shouldn't be entering to Button_Click event to find. Is there any way that I can find where it was clicked or not on Client Side and take it to Page_Load?
Background: Basically __EVENTTARGET and __EVENTARGUMENT , These two Hidden controls are added to the HTML source, when ever any autopostback attribute is set to true for any of the web control.
The __EVENTTARGET hidden variable will tell the server ,which control actually does the server side event firing so that the framework can fire the server side event for that control.
The __ EVENTARGUMENT variable is used to provide additional event information if needed by the application, which can be accessed in the server.
So we can easily get the control causing postback using:Request.Params.Get("__EVENTTARGET");
PROBLEM:
The method: Request.Params.Get("__EVENTTARGET"); will work for CheckBoxes, DropDownLists, LinkButtons, etc.. but this does not work for Button controls such as Buttons and ImageButtons
The Button controls and ImageButton controls does not call the __doPostBack function. Because of this, the _EVENTTARGET will always be empty. However, other controls uses javascript function __doPostBack to trigger postback.
So, I will suggest to do something as below. Add an OnClientClick property to the buttons. Also, define a hiddenField in your Markup, whose value will contain the actual button causing postback.
<asp:Button ID="Button1" runat="server" Text="Button"
OnClientClick = "SetSource(this.id)" />
<asp:ImageButton ID="ImageButton1" runat="server"
OnClientClick = "SetSource(this.id)" />
<asp:HiddenField ID="hidSourceID" runat="server" />
On the OnClientClick property of the Button and ImageButton Call the SetSource JavaScript function
<script type = "text/javascript">
function SetSource(SourceID)
{
var hidSourceID =
document.getElementById("<%=hidSourceID.ClientID%>");
hidSourceID.value = SourceID;
}
</script>
Here onwards, you can very easily check in your Page_Load as to which Control caused postback:
if (IsPostBack)
{
string CtrlName;
CtrlName=hidSourceID.Value;
}
I just got the same trouble, have to do some logic judgement in the Page_Load method to treat different event(which button was clicked).
I realize the arm to get the as the following example.
The front end aspx source code(I have many Buttons with IDs F2, F3, F6, F12.
<Button Style="display: none" ID="F2" runat="server" Text="F2:Cancel" OnClientClick="SeiGyo(this)" OnClick="F2_Click" />
<Button Style="display: none" ID="F3" runat="server" Text="F3:Return" OnClientClick="SeiGyo(this)" OnClick="F3_Click" />
<Button Style="display: none" ID="F6" runat="server" Text="F6:Run" OnClientClick="SeiGyo(this)" OnClick="F6_Click" />
<Button Style="display: none" ID="F12" runat="server" Text="F12:Finish" OnClientClick="SeiGyo(this)" OnClick="F12_Click" />
The back end aspx.cs source code, what I need to do is judge which button was clicked when Page_Load was triggered. It seems a little stupid, but works.
In your situation, the button be clicked will be added into dic. I hope that will be helpful to some one.
Dictionary<string, string> dic = new Dictionary<string, string>();
foreach(var id in new string[]{"F2","F3","F6","F12"})
{
foreach (var key in Request.Params.AllKeys)
{
if (key != null && key.ToString().Contains(id))
dic.Add(id, Request[key.ToString()].ToString());
}
}
The UniqueID of the button will be in Request.Form["__EVENTTARGET"]
This question is already answered at: ASP.NET : Check for click event in page_load
You can try using the hidden field. Make the client side event on the OnclientClick event and try setting the value of hidden field, may be true or false depending on the condition.
And on the page load you can check the value of Hiidden field.
function click()
{
// set the hidden field here
}
And on the page load, simply check the value.
if(HiddenFieldName.Value=="true")
{
//perform the action
}
private bool button1WasClicked = false;
private void button1_Click(object sender, EventArgs e)
{
button1WasClicked = true;
}
if ( button1WasClicked== false)
{
//do somthing
}

Method being triggered on page load but not via asp button

I have two asp:Labels, the first of which is replaced with a few buttons and the second with a list of items.
I want to click on the buttons to filter the items.
The contents of the buttons are added programmatically by replacing the text with html and works fine.
asp:
<form id="form1" runat="server">
<asp:Label id="filters" runat="server" Text="Filters here"/>
<asp:Label id="itemList" runat="server" Text="List of items here"/>
</form>
resultant html of filters label:
<input type="submit" onclientclick="Load_Items(0)" runat="server" value="First"/>
<input type="submit" onclientclick="Load_Items(1)" runat="server" value="Second"/>
<input type="submit" onclientclick="Load_Items(2)" runat="server" value="Third"/>
relevant c#:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Load_Items(0);
}
}
public void Load_Items(int filterType)
{
//code to load items (pseudo below)
for each row in list
if filterType = itemType
build string
replace second label with string
}
On page load everything happens just as I want it to with the contents being filtered by the first item (hence Load_Items(0)), and if I manually change the 0 to another number in Page_Load, it filters by the other types, but if I click the buttons which are programmatically added, nothing happens other than what looks like the page refreshing.
I know the post back check is working by adding a text replacement before and inside it.
I've also added an asp:button to make sure it's not something to do with the way the buttons are added as below (with some extra things recommended from searches):
<asp:Button runat="server" CausesValidation="False" onclientclick="Load_Items(2); return false;" text="Submit" />
So what could be the issue?
The OnClientClick property specifies the javascript to run in the browser when the button is clicked. Since you probably don't have a javascript function called Load_Items, this will generate a script error, and the button will then cause the form to post back.
The server-side Click event will fire on the server, but doesn't allow you to pass a parameter. You will only get the button instance and an empty EventArgs instance.
You might be better off using the Command event, combined with the CommandArgument property.
<asp:Button runat="server" CommandArgument="2" OnCommand="Load_Items" ...
The event handler would use the CommandArgument property of the CommandEventArgs to access the argument from the clicked button:
protected void Load_Items(object sender, CommandEventArgs e)
{
Load_Items(Convert.ToInt32(e.CommandArgument));
}
Well, that's the common problem which I think every asp.net developer deals some time. The common part of it, that asp.net event system doesn't work, as windows forms.
Page object, and all controls on that page, have lifecycle events, that are triggered during any request, even when it's from update panel.
As you create those controls by code, you have to keep in mind, that all events for those controls should work as part of Page object. That's why you have to create those object in Page_Init event, before all other control's event would be triggered.
Please also keep in mind that you have to create those controls as asp.net objects:
var btn = new Button();
But not by simply adding html markup. And you have to recreate them on each request, following that one, when they were created.
Please take a look on my another answer.

Page losing formatting

On my page a I have a few textboxes, AJAX tabpanel and a gridview.
In the Page_Load event, textboxes are filled in; gridview is populated and so on.
My gridview has a button:
<Columns>
<ItemTemplate>
<asp:Button ID="btnRedirect"
Text="Click me"
CommandArgument='<%#Eval("BkId_ZW")%>'
OnClick="DoRedirect"
runat="server" />
</ItemTemplate>
...
</Columns>
and the code behind it looks like:
protected void DoRedirect(object sender, EventArgs e)
{
Button theButton = sender as Button;
string url ="http://../profile/" + theButton.CommandArgument;
Response.Write("<script>window.open('" + url + "');</script>");
}
After button is pressed a new window is open (everything works as expected) but the main page loose values and formatting of the textboxes.
What is going on? How to fix it?
Response.Write() is not favored for this purpose. Since you are adding to the response in the middle of the ASP.net page lifecycle, you are changing the page output. If you view source, you might find your <script>window.open...</script> line in some awkward place.
Therefore, use Page.ClientScript.RegisterStartUpScript() instead.

Categories