Am trying to submit a webform pragmatically on button1 click. In first attemp ie after launching my webbrowser from visual studio it automatically submit the form but again clicking on button1, webpage loads but submit button is not invoked. While debugging its shows that the line of code executed but no action takes place.
private void button1_Click(object sender, EventArgs e)
{
webBrowser1.Navigate("xxxx");
webBrowser1.DocumentCompleted += webBrowser1_DocumentCompleted;
}
void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
if (webBrowser1.Url.OriginalString.ToString() == "xxxx")
{
if(webBrowser1.ReadyState==WebBrowserReadyState.Complete)
{
HtmlElementCollection doc = webBrowser1.Document.All;
foreach (HtmlElement ele in doc)
{
if (ele.GetAttribute("name").ToString()== "username")
{
ele.SetAttribute("value","xxxx");
}
if (ele.GetAttribute("name").ToString() == "password")
{
ele.SetAttribute("value", "xxxx");
}
if (ele.GetAttribute("classname") == "btn")
{
ele.InvokeMember("click");
}
}
}
}
textBox1.Text = webBrowser1.DocumentText;
}
You only want to setup the DocumentCompleted event for the web browser once. In your code you keep adding to the event chain each time the button is pressed which is not the behaviour you want.
You want something like (pseudo code as haven't got VS with me):
// When the form/parent loads bind the event ONCE here.
public void FormLoads()
{
webBrowser1.DocumentCompleted += webBrowser1_DocumentCompleted;
}
// Just navigate here and the event will still be raised
private void button1_Click(object sender, EventArgs e)
{
webBrowser1.Navigate("xxxx");
}
Its Due to your webBrowser1_DocumentCompleted Event is not working when your click on Button.
Just Create one method
Private Void Submit(); and here put your code which you want to perform on click event and call this method from two location one is at button1_click and another webBrowser1_DocumentCompleted so that your code is run at both events.
Related
I have a textbox and it's readonly. When I click on I want it to call my button click event:
private void tbFile_Click(object sender, EventArgs e)
{
//btnBrowse_Click(sender, e);
MessageBox.Show("test");
}
When click on the textbox, nothing happens. How do I fix it?
Update:
private void btnBrowse_Click(object sender, EventArgs e)
{
openFile();
}
private void tbFile_Click(object sender, EventArgs e)
{
//btnBrowse_Click(sender, e);
if (tbFile.Text != "")
{
openFile();
}
}
public void openFile()
{
var FD = new System.Windows.Forms.OpenFileDialog();
FD.Filter = "DBF Files|*.DBF";
FD.InitialDirectory = #"C:\";
if (FD.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
string fileToOpen = FD.FileName;
tbFile.Text = fileToOpen;
}
}
When I hit browse button and select a file, the browse file window comes up again. So it's appearing twice now and the textbox click is still not working.
There is no reason that can be inferred from the information you provided why you shouldn't trigger the openFile() method when you click on the tbFile control.
The fact that the textbox is set to readonly does not stop it from raising the click event in any way.
The only possibility is that the method is not assigned to the click event of the control.
Make sure in the event properties of the control that the click event is indeed assigned to the "tbFile_Click" method.
Just because there exsits a method that's called the same as a control but has "_Click" added does not make it get executed unless you specifically tell c# you want to associate that method with the click event of the control.
When you assign the method through the event window, C# generates a code file behind the scenes that adds the callback to that specific event.
You should use the btnBrowse.PerformClick() method to simulate a user click, instead of calling the handler.
The default I got from VS 2013 was a 'MouseClick' function so this works:
private void btnBrowse_Click(object sender, EventArgs e)
{
MyAwesomeFunction(sender);
}
private void tbFile_MouseClick(object sender, MouseEventArgs e)
{
MyAwesomeFunction(sender);
}
private void MyAwesomeFunction(object sender)
{
MessageBox.Show("test");
}
I have a user control on an aspx page that contains filter fields and return a WhereClause. The user conrol will raise an event called FilterApplied when Search is clicked.
On my main form, I add the control with:
<uc1:Filter runat="server" ID="Filter" />
<br />
In my code behind I have:
protected void Page_Load(object sender, EventArgs e)
{
//Register event when filter is changed.
this.Filter.FilterApplied += new EventHandler(this.FilterApplied);
if (Page.IsPostBack)
{ //Do some things that take long
}
}
protected void FilterApplied(object sender, EventArgs e)
{
//Reload the page to refresh the graphs.
Page_Load(sender, e);
}
Problem is:
When I click Search on my user control, the Form_Load runs twice. Once because it is reloaded and then another time because I call it from FilterApplied. If I don't call it from FilterApplied, then the whereclause is still empty.
How can I ensure the Page_Load only run once when Search is clicked?
Your problem lays in multiple registering for FilterApplied event. Each time you call the Page_Load method, you subscribe to this event again. Here is a really simple example of what you are doing, written in WinForms with one button on the form, just to point out your problem:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private int numClicks = 0;
private void Form1_Load(object sender, EventArgs e)
{
button1.Click += button1_Click;
this.Text = numClicks.ToString();
}
private void button1_Click(object sender, EventArgs e)
{
numClicks++;
//try uncommenting and commenting next line of code, and observe the difference:
//button1.Click -= button1_Click;
Form1_Load(sender, e);
}
}
I have a simple C # application that contains buttons and a web browser, each button execute a request and displays the result of the request on the web browser. And use the results of a request in the next button.
private void button1_Click(object sender, EventArgs e)
{
webBrowser1.Navigate("http://www.test.com");
}
private void button2_Click(object sender, EventArgs e)
{
if (webBrowser1.Document.GetElementById("tesxtbox1") != null)
{
HtmlElement txt1 = webBrowser1.Document.GetElementById("tesxtbox1");
txt1.SetAttribute("value", "test");
webBrowser1.Document.Forms[0].InvokeMember("submit");
}
}
Is there any method or way to perform the two buttons with a single click, but the second button, do not execute until the web browser is loaded.
in the first button, I added
webBrowser1.DocumentCompleted + = new WebBrowserDocumentCompletedEventHandler (Button2_Click);
but the second button excuted several times, so I added in the last line of the button 2:
webBrowser1.DocumentCompleted - = new WebBrowserDocumentCompletedEventHandler (Button2_Click);
it works, but in the console I find that Button 2 is execute twice
Thanks in advance!
You shouldn't think like executing second button click. There is DocumentCompleted event which you must listen to and execute neccesary code afterwards.
private void button3_Click(object sender, EventArgs e)
{
webBrowser1.DocumentCompleted += (sender, e) => {button2_Click(sender, e);};
button1_Click(sender, e);
}
will register the button2_Click method to be executed after the document is loaded completely as triggered by button1_Click().
You should add an event that will call the code once the document has completed loading.
private void Form1_Load(object sender, EventArgs e)
{
webBrowser1.DocumentCompleted += webBrowser1_DocumentCompleted;
}
void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
button2_Click(sender, e);
}
You could make the following call from your button1_click method.
button2_Click(sender, e);
You could give an argument in the url:
webBrowser1.Navigate("http://www.test.com?excuteSecondButton=Yes");
Then on the second page you check if that argument was given:
PageLoad()
{
if(Request.QueryString["executeSecondButton"].Equals("Yes"))
{
button2_Click(button2, new RoutedEventArgs());
}
}
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 want to create a method in code behind that creates a button and places it in a PlaceHolder. I want this button to have a Click event.
After calling the "test" method button is placed correctly but the click event is not called.
private void test()
{
Button linkBtn1 = new Button();
linkBtn1.Text = "linkBtn1";
linkBtn1.OnClientClick = "return false;";
linkBtn1.Click += new EventHandler(linkBtn1_Click);
PagesPlaceHolder.Controls.Add(linkBtn1);
}
void linkBtn1_Click(object sender, EventArgs e)
{
throw new NotImplementedException();
}
Removing the OnClientClick = "return false;" is necessary but not sufficient to get this to work. If you want the event handler on the dynamically added button to be triggered, you'll need to add this button every time the page loads.
One simple way would be to save the fact that the button has been added in ViewState, and then check that on PageLoad, and re-add the button if needed.
Here's a sample that works for me (and throws the exception when clicked)
protected void Page_Load(object sender, EventArgs e)
{
//if the button was added previously, add it again
if (ViewState["Added"] != null && (bool)ViewState["Added"])
addButton();
}
//this is the method that adds the button
protected void add_Click(object sender, EventArgs e) {
ViewState["Added"] = true;
addButton();
}
private void addButton() {
Button linkBtn1 = new Button();
linkBtn1.Text = "linkBtn1";
linkBtn1.Click += new EventHandler(linkBtn1_Click);
placeholder1.Controls.Add(linkBtn1);
}
void linkBtn1_Click(object sender, EventArgs e) {
throw new Exception("Button Click Event Triggered. Hello yellow screen!!!");
}
As #oleksii points out, have the clientside code is returning false so the form never gets submitted. You need to comment this out, then your event handler should fire.