C# / asp.net global Variables? - c#

I have two buttons with on click functions
The 1st one gets assigned a variable when Clicked.
How do I get my second button to get the variable from the 1st button when I click button 2?
It doesn't seem to work. As the second button doesn't recognise the Variable.
Thanks
EDIT:
Just to clarify My code is generating a pdf. button 1 selects the url of the template to use. and in button 2 (the one generating the pdf) I want it to get the variable set from button 1 so it knows what template to use.
EDIT 2:
My code does work but only when I'm not using the ajax update panel. it seems that the variable I'm trying to set doesn't get set with AJAX

Your Button have Id, you get this button with his Id
Nota : You can add runat="server" in order to visualize in server side
<asp:Button id="Button1"
Text="Click "
OnClick="Btn1_Click"
runat="server"/>
<asp:Button id="Button2"
Text="Click "
OnClick="Btn2_Click"
runat="server"/>
void Btn2_Click(Object sender, EventArgs e)
{
Button1.Text = "test after click on button 2";
Template = ...;//Set your value
}
void Btn1_Click(Object sender, EventArgs e)
{
Button2.Text = "test after click on button 1";
//Here you can get your value after post.
var result = Template;
}
It's not subject but in delegate you can also get objet button by passing on sender argument.
var button = sender as Button; //You get button who raise event
In order to manage Template Path property.
public string Template
{
get
{
if(ViewState["Template"] != null)
{
return (string)ViewState["Template"];
}
}
set{ViewState["Template"] = value;}
}

i guess you are looking at accessing value of a variable inside the click event of button2 for which the value is set in the button1 click event ?
private string myPrivateString = "";
void Page_Load()//Not sure of correct method signature
{
if(Page.IsPostBack)
{
myPrivateString = Session["myPrivateString"];
}
}
void Button1_Click(object sender, EventArgs e)
{
//There will a postback before this gets executed
myPrivateString = "Value Set From Button 1";
Session["myPrivateString"] = myPrivateString;
}
void Button2_Click(object sender, EventArgs e)
{
//There will a postback before this gets executed
//Accessing myPrivateString here without setting value from session
//will return empty string as after PostBack its a new page thats rendered.
myPrivateString = Session["myPrivateString"]; // Or do it in the Page_Load event
}
I guess now you can get the value of inside the button2 click event.
Also read about ASP.NET Page lifecycle and how client side events like button clicks are handled by the ASP.NET framework.

Related

Disable Required validation for a specific button & textbox

I want to disable required validator field for a specific button click which is not check only a textbox. i've tried this code in the button click but not worked. so need this type of code how solve.
protected void Button3_Click(object sender, EventArgs e)
{
if (TextBox1 == null)
{
RequiredFieldValidator1.EnableViewState = false;
}
}
Just set CausesValidation="false" on your button property.
If you wish to validate that particular button with some other TextBox or control you can set ValidationGroup="groupA" to those controls and name it same group.

Client Interaction in WebForms

What way is standard/ recommended to do the following:
When a user raises the Page_Command "Save" or "Send," I want to run a method. If the method returns false, I want to send the user back to the page and display a message.
All of the data they entered in the form should still be there. The message would have a button that reads, "Send Anyway/ Regardless." If they click it, it will send.
I know I could do this via a webservice and jQuery, but I am asking how I would do this via WebForms.
Here is my basic code:
protected void Page_Command(Object sender, CommandEventArgs e)
{
if ( e.CommandName == "Save" || e.CommandName == "Send" )
{
// run method
}
}
There are several ways you could do this.
One option might be to a button with the text "Save", and another with the text "Send anyway". Make the second button invisible to begin with, and the first visible.
When the first button is clicked, it should run the validation-logic. If validation succeeds, submit - otherwise, hide the first button, and set the other one to visible.
When / if the second button is clicked, the submit is performed without validation.
Update:
With some minor modifications, you should be able to do something like this:
Markup:
<asp:Button runat="server"
ID="myFirstButton"
OnClick="SubmitWithValidation" />
<asp:Button runat="server"
ID="mySecondButton"
Visible="False"
OnClick="SubmitData" />
Code:
protected void SubmitWithValidation(object sender, EventArgs e)
{
if (ValidateMyData())
{
SubmitData(sender, e);
}
else
{
mySecondButton.Visible = true;
myFirstButton.Visible = false;
}
}
private bool ValidateMyData()
{
// Validate stuff
return isValid;
}
private void SubmitData(object sender, EventArgs eventArgs)
{
// Logic to submit your data here
}

Handling an event on a dynamically-added Button after postback

Basically, I have an update panel in which i have a link button, when user clicks on the link button all the contents are cleared and textbox shows up in which user enters something and when user hit enter key, the update panel should be refreshed or gets updated or repopulated with all the contents .
How can I do it ???
The way I am trying to do this is that when event handler of link button is fired, I created a hidden button dynamically and assign it a new event handler which will get fired when user hits enter key.This new dynamic button is created inside link button event handler. In this new button event handler I will repopulate the contents back.
The problem with my way is the event handler of dynamically created button is not fired.
Why ???
Please try to answer in c#.
Thanks in advance.
Regards,
My code #
protected void Submit_Click1(object sender, EventArgs e)
{
Label1.Text = TextBox1.Text + TextBox2.Text + " are sucessfully registered";
Button mento = new Button();
mento.cssclass = "invisible";
mento.Click += new EventHandler(mento_click);
// here this new mento button is attached to update panel
updatepanel1.ContentTemplateContainer.Controls.add(mento);
}
Now the problem is mento_click event handler does not get fired ???
You can catch the enter key, in the textbox?
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
//add event keydown
textBox1.KeyDown += new KeyEventHandler(textBox1_KeyDown);
}
void textBox1_KeyDown(object sender, KeyEventArgs e)
{
switch (e.KeyCode )
{
case Keys.Enter:
//YOur updatecode here:
MessageBox.Show("You press enter");
break;
default:
break;
}
}
}
You have to attach the event on page_init or page_load every time theres a request, or the event wont get hooked up to the control.
you can check out this link to understand why:
http://msdn.microsoft.com/en-us/library/ms178472.aspx
Example
if you want to hook it up on the submit you should do something like:
page_init(object sender, EventArgs e)
{
CreateControls();
}
private void CreateControls()
{
//Create button with event and add to the panel
}
clickEvent(object sender, EventArgs e)
{
updatePanel.Update();
}
That should fire correctly the event. Im sorry i just wrote this on the fly and didnt test it, but i hope it gives you de general idea.
Cheers.
To all of you strugling with postback from buttons in asp.net, I would like to mention an alternative and ancient method of dealing with button-click events.
1) name your dynamically created buttons using a Prefix (like for instance this one: btn_). That way, every button you create will have a name starting with this prefix. For example the first button you create will have the name btn_0. You can achieve this by a routine like this one:
For _counter As Integer = 0 To 3
Dim butt As New Button
' the next 1 line is convenient when programming for the .net 4.0 framework:
butt.ClientIDMode = UI.ClientIDMode.Static
butt.butt.ID = "btn_" & _counter
butt.Text = "someting"
page.controls.add(butt)
next
2) ... and then, to handle it all, you can do it like this in the on_load event of your asp.net page:
If IsPostBack Then
For Each key As String In Request.Form
If InStr(Trim(key), "btn_") > 0 Then
Response.Write(Request.Form(key))
End If
Next
End If

linking to a radiobutton value, data is not binding, asp.net c#

hi i need to modify my code a little bit. i have a page with a radio button list and a textarea. the textarea is populated when a users makes a radio button selection.
also, when a user makes a radio button selection the url will hold an extention in the url to show which selection index number they have selection. (i.e. ?selected=0)
http://test.com/frm_Articles.aspx?selected=0
http://test.com/frm_Articles.aspx?selected=1
http://test.com/frm_Articles.aspx?selected=2
that way they can copy the url and reference it in other websites as a link. or place it in their favorites.
the problem is, if you grab the url and open a new browser, the page does not pass the value and databind accordingly. no radio buttons or content appear on the page.
must be the postback logic i think???
what's working:
when i launch the website the radio buttons appear and index 0 is set
when i select radio buttons the correct data displays and urls linking to radio button values display in browser (i.e. http://test.com/test.aspx?selected=2)
if i cut and paste pointer urls within the same browser then correct data is rendered
what doesn't work (everything that deal with an false PostBack):
1.when i launch website no data within the textarea apprears even though the radio button is set to 0 index and is visiable.
2. if i cut and paste pointer url into a new browser, text area and radio buttons do not display.
protected void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostBack == false)
{
int selected;
if (Request.QueryString["selected"] != null)
{
if (int.TryParse(Request.QueryString["selected"], out selected))
{
RadioButtonList1.SelectedIndex = selected;
RadioButtonList1.DataBind();
}
}
else
{
int firstart = 0;
RadioButtonList1.SelectedIndex = firstart;
RadioButtonList1.DataBind();
}
}
}
protected void SqlDataSource2_Selecting(object sender, SqlDataSourceSelectingEventArgs e)
{
//
}
protected void SqlDataSource1_Selecting(object sender, SqlDataSourceSelectingEventArgs e)
{
try{
e.Command.Parameters["#URL_FK"].Value = Session["URL_PK"];
}
catch (Exception ex)
{
}
}
protected void RadioButtonList1_SelectedIndexChanged(object sender, EventArgs e)
{
string strRedirect;
strRedirect = "test.aspx?selected=" + RadioButtonList1.SelectedIndex;
Response.Redirect(strRedirect);
}
}
In your code at Page_Load event before this line
RadioButtonList1.SelectedIndex = selected;
you should bind RadioButtonList1. after binding RadioButtonList you can set SelectedIndex.
my SqlDataSource1_Selecting method was the issue. i used another approach and my code worked.

get submit button id

Inside asp.net form I have few dynamically generated buttons, all of this buttons submit a form, is there a way to get which button was submit the form in page load event?
The sender argument to the handler contains a reference to the control which raised the event.
private void MyClickEventHandler(object sender, EventArgs e)
{
Button theButton = (Button)sender;
...
}
Edit: Wait, in the Load event? That's a little tricker. One thing I can think of is this: The Request's Form collection will contain a key/value for the submitting button, but not for the others. So you can do something like:
protected void Page_Load(object sender, EventArgs e)
{
Button theButton = null;
if (Request.Form.AllKeys.Contains("button1"))
theButton = button1;
else if (Request.Form.AllKeys.Contains("button2"))
theButton = button2;
...
}
Not very elegant, but you get the idea..
protected void Page_Load(object sender, EventArgs e) {
string id = "";
foreach (string key in Request.Params.AllKeys) {
if (!String.IsNullOrEmpty(Request.Params[key]) && Request.Params[key].Equals("Click"))
id = key;
}
if (!String.IsNullOrEmpty(id)) {
Control myControl = FindControl(id);
// Some code with myControl
}
}
This won't work if your code is inside a user control:
Request.Form.AllKeys.Contains("btnSave") ...
Instead you can try this:
if (Request.Form.AllKeys.Where(p => p.Contains("btnSave")).Count() > 0)
{
// btnSave was clicked, your logic here
}
You could try:
if (this.Page.Request.Form[this.btnSave.ClientID.Replace("_", "$")] != null) {
}
please try this code in page load event
string eventtriggeredCategory = Request.Form["ctl00$ContentPlaceHolder1$ddlCategory"];
if eventtriggeredCategory is returning any value its fired the event of ddlCategory
this is works fine for me
Thanks
Jidhu
Request.Form["__EVENTTARGET"] will give you the button that fired the postback
Use CommandArgument property to determine which button submits the form.
Edit : I just realized, you said you need this at PageLoad, this works only for Click server side event, not for PageLoad.

Categories

Resources