Is there any possible way to eliminate repeated lines by calling a function for many buttons in (aspx.cs) asp.net. I have tried through class, but elements of WebForm cannot be called. Is there any other way?
txtDescription.Text = "";
txtProjectDate.Text = "";
rblProjectStatus.SelectedIndex = -1;
txtProjectName.Text = "";
txtWebsiteUrl.Text = "";
calProjectDate.Visible = false;
chkProject1.Selected = false;
chkProject2.Selected = false;
ddlCompanyName.Items.Insert(0, new ListItem("--Select Name--"));
This code have to be inserted into a function, so that I can call the function wherever necessary. Is it possible ?
partial class MyPage
{
protected override void MyButton_Click(object sender, EventArgs e)
{
ResetControls();
}
protected override void MyOtherButton_Click(object sender, EventArgs e)
{
ResetControls();
}
private void ResetControls()
{
// do your business here
}
}
Alternatively you can hook both buttons to the same handler if they are to have identical behavior.
Looks like you are trying to reset the form. You should do this way (a button on web page):
<input type="reset" />
Another alternative is to redirect to the current url (from your C# code):
Page.Response.Redirect(Page.Request.Url.RawUrl)
Related
Let me elaborate on this... I have the code below, there is a Page_Init (which I still don't understand why it fires more than once, but that is another story), and a Page_Load and I am checking for the "isPostBack" ... everything works great while I use my controls, radio button and drop down list, as well as Buttons; however, if I press the key, even accidentally, the "isPostBack" is reset to False. What am I doing wrong? Also, my AutoEventWireup="true".
Also, this is an .ascx file.
protected void Page_init(object sender, EventArgs e)
{
LoadPageText1();
paymntpnl1.Visible = true;
curbalpnl.Visible = false;
paymntpnl2.Visible = false;
paymntpnl3.Visible = false;
paymntpnlcc.Visible = false;
}
protected void Page_Load(object sender, EventArgs e)
{
LoadPageData();
getContractInfo();
step2lbl.BackColor = System.Drawing.Color.White;
nopmt = Convert.ToDecimal(numpmts.Text);
nopmt = nopmt * nopymts2;
sb.Clear();
sb.Append("$");
sb.Append(nopmt.ToString("#.00"));
nopymts.Text = sb.ToString();
ValidateCC();
chkNewCC();
bool crdcrd = credCard;
bool newcrd = nwCard;
if (!IsPostBack){
}
}
You're checking IsPostBack but you're still doing all the resetting before the check! And then the check makes no difference because it's an empty conditional block! You should be doing this:
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
// All the initial setup that you don't want to do again goes here.
}
// All the stuff you want to do on first load AND PostBack goes here.
}
Make sure you understand how conditionals work.
I need to write a code that can intercept a click of some button (asp button) than execute some code, and if a method return true, call the original click.
So the points are:
1- I don´t know how to save the original click.
2- Identify the button that was clicked.
Ex:
protected void Page_Load(object sender, EventArgs e)
{
var b = getButtonThatWasClicked();
var originalClick = b.Click;
if(callSomeMethod(b))
originalClick(null,null);
}
EDIT:
Ok managed to get the button who made the click doing this...Now i need to prevent the original Click to get called. The method bellow didn't worked. Even overriding the original click to a new Handler the old Handler got called and executed. I thing ASP.NET read it and make something like a call stack of events to get called.Even if the handler change the old still in the stack.
public void ButtonsTestMethod()
{
var listOfButtons = listaDeBotes.Where(b => b.CommandName != "");
foreach (var button in listOfButtons)
{
if (Request.Form[button.UniqueID] != null)
{
var buttonFromRequest = Request.Form[button.UniqueID];
if (buttonFromRequest == null)
continue;
if (button.CommandName != "xxx")
{
//validate things
//if(TemPermissao(Tela,GetAcaoDoBotao(botao.CommandName)))
//if(!canexecuteSomething())
button.Click += new EventHandler(defaultClick);
}
}
}
}
void defaultClick(object sender, EventArgs e)
{
//show error
}
protected void Page_Load(object sender, EventArgs e)
{
//other code
ButtonsTestMethod();
}
I don´t know if its possible but would appreciate some help =/
Thanks.
To get the control name, you can try the following in the page load:
protected void Page_Load(object sender, EventArgs e)
{
if( IsPostBack )
{
string senderControl = Request.Params["__EVENTTARGET"].ToString();
//senderControl will contain the name of the button/control responsible for PostBack
}
}
The first argument in the button click event handler is the sender. You can cast that sender as a Button object and then you should be able to identify which button that was based on that object. That way, you can eliminate having that function to figure out which is clicked.
void GreetingBtn_Click(Object sender, EventArgs e)
{
Button clickedButton = (Button)sender;
if(clickedButton.Text == "bla")
{
//Do stuff
}
}
I have the following code behind:
public partial class _Default : System.Web.UI.Page
{
List<GlassesCollection> gc= BL.Example.GetCategory() ;
protected void Page_Load(object sender, EventArgs e)
{
rpt1.DataSource = gc;
rpt1.DataBind();
}
protected void rpt1_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
Button btn = (Button)e.Item.FindControl("btn1");
btn.CommandArgument = DataBinder.Eval(e.Item.DataItem,"CollectionID").ToString();
}
}
I want to pass the content of the btn.CommandArgument to Label's event that placed in another ASPX.CS file.
Is there any way to implement this?
Thank you in advance!
You need to use Session. Put value in Session and read it in another page.
Session["key"]=value;
You can use QueryStrings. For example, your url will can look like:
string url = String.Format("http://www.example.com/somepage.aspx?labeltext={0}",btn.CommandArgument);
Then, in your somepage.aspx, you can have:
//"labeltext" is the same name we used above as the ID
string lblText = Request.QueryString["labeltext"];
if (lblText != null)
{
myLabel.Text = lblText;
}
If there's a chance that the text might not be suitable for passing in a URL, you can encode it with HttpServerUtility.UrlEncode and then decode it with HttpServerUtility.UrlDecode before assigning it to the label.
Use the query string for that:
Response.Redirect("AnotherPage.aspx?CommandArgument=SomeArgument");
Then read the QueryString on AnotherPage.aspx
string commArgument = Request.QueryString["CommandArgument"];
What is the best way to distinguish beteen "Refresh Post" or a "Real Post Back".
This is what I need to attain
protected void Button1_Click(object sender, EventArgs e)
{
if(PostBack && !Refresh)
{
//Do Something
}
}
I usually do a Response.Redirect to the same page in the postback event.
That way all my Page.IsPostBack are real Postbacks and not Refreshes
You could set a hidden input with a nonce value generated randomly every time the form is loaded (but not on postback), then check if the nonce value got sent twice. If it got sent a second time, it was a refresh.
you could try like
protected void Button1_Click(object sender, EventArgs e)
{
//your code of Click event
//..............
//...............
// and then add this statement at the end
Response.Redirect(Request.RawUrl); // Can you test and let me know your findings
}
Sample working code for the accepted answer
Add this line in designer
<input type="hidden" runat="server" id="Tics1" value="GGG" />
Add following lined in the code behind
public partial class WebForm1 : System.Web.UI.Page
{
long tics = DateTime.Now.Ticks;
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
this.Tics1.Value = tics.ToString();
Session["Tics"] = tics;
}
}
protected void Button1_Click(object sender, EventArgs e)
{
if (Session["Tics"] != null && Request["Tics1"] != null)
{
if (Session["Tics"].ToString().Equals((Request["Tics1"].ToString())))
{
Response.Write("Postback");
}
else
{
Response.Write("Refresh");
}
}
this.Tics1.Value = tics.ToString();
Session["Tics"] = tics;
}
}
am wondering why this code fails to focus the textbox...?
private void sendEmail_btn_Click(object sender, EventArgs e)
{
String sendTo = recipientEmail_tbx.Text.Trim();
if (!IsValidEmailAddress(sendTo))
{
MessageBox.Show("Please Enter valid Email address","Cognex" MessageBoxButtons.OK, MessageBoxIcon.Error);
recipientEmail_tbx.Focus();
}
}
Use Select() instead:
recipientEmail_tbx.Select();
Focus is a low-level method intended primarily for custom control authors. Instead, application programmers should use the Select method or the ActiveControl property for child controls, or the Activate method for forms.
http://msdn.microsoft.com/en-us/library/system.windows.forms.control.focus.aspx
Add Delay some miliSec. Delay then call Focus() and Not forget to put inside Dispatcher.
Task.Delay(100).ContinueWith(_ =>
{
Application.Current.Dispatcher.Invoke(new Action(() =>
{
TextBoxNAme.Focus();
}));
});
Even I tried with lots of above solutions but none of them worked for me as am trying to focus on page load. Finally I got this solution and it worked.
private void txtBox_LayoutUpdated(object sender, EventArgs e)
{
txtBox.Focus();
}
Use the Form_Activated event handler, in conjunction with a firstActivation boolean.
private bool firstActivation = true;
private Control firstWindowsControl = null;
...
private void DynamicForm_Activated(object sender, EventArgs e)
{
if (firstActivation)
{
firstActivation = false;
bool fwcPresent = (firstWindowsControl != null);
Console.WriteLine($"DynamicForm_Activated: firstWindowControl present: {fwcPresent}");
if (fwcPresent)
{
firstWindowsControl.Focus();
}
}