I am creating a button in the code behind of my aspx.cs page. However I need to detect within this textbox when any text is changed within it after it has been created.
TextBox addn = new TextBox
{
ID = "Tb_Address" + i,
CssClass = "TextBoxProfile",
OnTextChanged = "textChangedEventHandler",
Text = "testc"
};
Tb_Container.Controls.Add(addn);
However OnTextChanged gives me this error:
'System.Web.UI.WebControls.TextBox.OnTextChanged(System.EventArgs)' is inaccessible due to its protection level
I have read around these issues; but I don't have a designer page to change the protection level, neither do I think that would work as these controls are created programmatically.
Edit:
I had tried:
addn.OnTextChanged += textChangedEventHandler;
However this still gives me the above error.
addn.TextChanged += textChangedEventHandler;
The above works, but it's not the desired output, as I wish for this to be automatic and not on PageLoad(?).
OnTextChanged is a method, not an event, you can't subscribe to this, it is the method that raises the event. It is protected so that if you derive from the Textbox class, you can override with your own behaviour. See OnTextChanged method.
TextChanged is the actual event itself that you need to subscribe to, you had done this correctly, but I think you expected it to behave differently? How did you expect it to behave? Netnetter might be on the right lines of using javascript. See TextChanged event.
addn.TextChanged += textChangedEventHandler;
The above works, but it's not the desired output, as I wish for this to be automatic and not on PageLoad(?).
You are subscribing to the text-changed event in way you do it in the ascx file. Since you creating the controls programmatically, you should subscribe to the event like this:
TextBox addn = new TextBox {
ID = "Tb_Address" + i,
CssClass = "TextBoxProfile",
Text = "testc"
};
addn.OnTextChanged += textChangedEventHandler;
Tb_Container.Controls.Add(addn);
you can directly attach event as shown below and take an event handler... and take a look at this answer Dynamically create an ImageButton :-
TextBox addn = new TextBox ;
addn.TextChanged += new EventHandler(b_textChanged);
and its handler :-
void b_textChanged(object sender, EventArgs e)
{
////Your code
}
addn.TextChanged += textChangedEventHandler;
The above works, but it's not the desired output, as I wish for this to be automatic and not on PageLoad(?).
Do you mean that the text change should be detected as you are typing in the values?
because if you mean that then JavaScript is what you need.
Related
I'm having problems adding an event to an ImageButton. I have to create a set of buttons depending on a selected option from a DropDownList. The buttons are created successfully with Database data, but I'm can't attach the OnClick functionality.
The created buttons must share the same Handler.
protected void cmbServ_SelectedIndexChanged(object sender, EventArgs e) {
ServiceID = cmbServ.SelectedValue.ToString();
ServiceName = cmbServ.SelectedItem.ToString();
DataTable dtFirstTab = new DataTable();
dtFirstTab = mySQLConn.getTable(qryCarry); // LOAD DATA FROM DB
foreach (DataRow row in dtFirstTab.Rows) {
FTabBtn = "btn"+(Convert.ToInt32(row["SKU_Credito"])).ToString();
FTabIconURL = row["SKU_Icon"].ToString();
Panel dvFirstTab = new Panel();
dvFirstTab.CssClass = "col-xs-2";
ImageButton IB = new ImageButton();
IB.ID = FTabBtn;
IB.ImageUrl = FTabIconURL;
IB.Click += new ImageClickEventHandler(btnX_click); // <-- PROBLEM
dvFirstTab.Controls.Add(IB);
pnlIcons.Controls.Add(dvFirstTab); // pnlIcons exists in HTML
}
protected void btnX_click(object sender, ImageClickEventArgs e) {
string Obj = ((ImageButton)sender).ClientID;
Cantidad = Convert.ToInt32(Obj.Substring(3, (Obj.Length) - 3));
txtMonto.Text = "$" + Cantidad.ToString();
}
All the buttons appear correctly, but when I click on them they just fire a "submit" action, acting like there's no OnClick assigned.
No CodeBehid example:
If I add this line in HTML (I removed asp tags)
ImageButton ID="btn10" runat="server" ImageUrl="MontoLogo_10ST.png" OnClick="btnX_click"
It does work as intended.
Any ideas? Thanks a lot!
Creating controls dynamically in ASP.NET webforms usually seems easy at the beginning, but problems are very common when it comes to handling events. Even if you assign your event handler correctly, the event handler is not run in a postback until you re-create all the dynamic controls early in page lifecycle. This explains why the sample with the ImageButton on the ASPX works whereas the dynamically created buttons don't.
See this page for details on creating controls dynamically. The most important part is the warning that basically says: if you need to add dynamic controls, better don't.
Usually you can find a way to create all the necessary controls in markup, for instance using a Repeater control. The big advantage of the repeater is that you have control about the markup that is created.
The following sample outlines the necessary steps:
Place a repeater on your aspx-page. If pnlIcons serves no other purpose than being the container for the dynamically created buttons, substitute it by the repeater. Use the Header- and FooterTemplate properties to add the markup that surrounds the ImageButtons (e.g. the div for dvFirstTab).
Think about which data you need to assign to the image button. In your case, the fields "SKU_Credito" and "SKU_Icon" seem to be required.
Place the Image button in the ItemTemplate of the repeater and bind the properties "Id" and "ImageUrl" to the corresponding fields.
Add a Command event handler and bind the CommandArgument property to a value that helps you discern between the image buttons.
In the command event handler, you can use the CommandArgument to discover which button has been clicked. Add the appropriate code that handles the command.
In the SelectedIndexChanged event handler, read the data from the database and bind the repeater to the result. This creates the rows in the repeater with the ImageButtons.
Ok, I've found the reason. The event handling must be assigned in Page_Load event, so I moved everything inside a method and called it from Page_Load, calling it from "SelectedIndexChanged" doesn't work . It's working now.
Thanks!
I am having a problem with having the eventhandler textchanged method to work with an array of textboxes. The textboxes are generated through C# and not through ASP.NET.
here is the TextBox code in C#:
int i = 1;
foreach(string a in data)
{
i++;
TextBox text = new TextBox();
text.TextChanged += new EventHandler(updateone);
text.AutoPostBack = true;
text.ID = Convert.ToString(i);
}
I tried out the Text.AutoPostBack false and true and I had the same result. The updateone method is not even touched when I change the text of the textbox. When I do change the text
of the textbox it does update the website, but again the updateone method is not even touched in the code. Here is the updateone code:
protected void updateone(object sender, EventArgs e)
{
TextBox text = (TextBox)sender;
}
I thank everyone for their help! I am just confused why this is not working... and also I have to use the C# method and not the ASP.NET way.
have you tried storing references to your TextBoxes in an instance member so that they don't get garbage collected?
something like:
List<TextBox> textBoxes = ...
//in a loop
text.ID = Convert.ToString(i);
textBoxes.Add(text);
-- edit
also, as a rule of thumb, put as much logging in your application as possible.
Whether it is NLog, any other logging tool or even a simple Console.WriteLine(), seeing what your code is actually doing is very helpful.
Since you've confirmed that you're posting your actual code and don't seem to get what I'm trying to say, let me try to explain in an answer.
First problem: Your array of TextBoxes does not exist, which the other answer has already addressed and you've apparently fixed but haven't updated the code in your question to show your fix.
Second problem: The TextBoxes you create are not being added to your form in any way. I'm not sure how you're testing your event handler without doing that.
Third problem: Your event handler updateone doesn't do anything. Imagine you walk into a grocery store, pick up an orange, put it back down, and then leave. That's what your event handler is doing. Instead of just instantiating a temporary TextBox and then doing nothing, try making a message box pop up, or changing the text of another control that exists on the form.
Maybe something like this will work:
List<TextBox> textboxes = new List<TextBox>();
int i=1;
foreach(string a in data) // I assume data is a list or array of strings
{
// I'm not sure why you iterate over data if you don't use it at all inside the loop...
++i;
TextBox text = new TextBox();
text.TextChanged += new EventHandler(updateone);
text.AutoPostBack = true;
text.ID = Convert.ToString(i);
// Add the TextBox to form here, not sure what the call is
}
Label info = new Label;
Label.Text = "Hello!";
// Add Label to form here, again not sure what the call is
And then your event handler:
protected void updateone(object sender, EventArgs e)
{
info.Text = ((TextBox)sender).Text;
}
You are dynamically creating ASP.NET controls. This means that they will not be automatically re-created on the postback of the form. Also, the controls have to be created in the Page_Init event, not the Page_Load event.
So the question is, where and when are you creating the textboxes. Make sure they are created at the Page_Init stage, and you are creating them in the request and in the postback.
So my problem is that I want to add an event handler to a dynamically created CheckBox. I have already looked at other ways to do this, and decided that creating a dynamic table which contains my CheckBoxes is the best option for me. I have not added these CheckBoxes to the Control Tree because I need to manage the ViewState manually. Either way, my code works in every way except that my CheckBox's CheckChanged Event does not fire. I am adding this eventhandler to my CheckBox in my pageLoad event, however, any page event I try seems to give me the same results:
CheckBox chbxLv1 = new CheckBox();
chbxLv1.ID = "DymanicallyCreatedIDForIdentification";
chbxLv1.AutoPostBack = true;
chbxLv1.CheckedChanged += new EventHandler(this.checkChanged);
/* Way lower in my code */
protected void checkChanged(object sender, EventArgs e)
{
//Some code goes here which never seems to execute... grrr
}
I thought that this may be a problem with the ViewState at first and did quite a bit of research on that. I'm now thinking I am doing something dumb with adding an event handler. I'm not sure why this event never fires, but I'm a little new at adding events to a control. Do I need a delegate here?
--Roman
In order for dynamically loaded controls to be handled properly during the ASP.NET Page Lifecycle, they need to be added to the page during OnInit (or prior to LoadViewState, really) otherwise their state information will not be maintained and you can, in fact, corrupt the viewstate depending on how/where things are added in the page's control graph.
Is there any event that fire when the value of the textbox change from a peace of code and when the textbox is validated or lost the focus and the event don't fire on the key press,because I have a lot of calculation and It's not possible to do it on every key press
Use TextChanged for text changed.
Use LostFocus for when textbox looses focus.
Use Validating or Validated for validation.
Here is the order in which events are called for TextBox:
// Reference : http://msdn.microsoft.com/en-us/library/system.windows.forms.control.validated.aspx
1) Enter
2) GotFocus
3) Leave
4) Validating
5) Validated
6) LostFocus
This should help you decide where you want to put your code.
There's no event that will fulfill your requirement of being raised when the textbox's value is changed programmatically through code, but not when text is typed into it by the user. The TextChanged event is going to be raised either way (this is fairly intuitive—the text value is changing, and the computer doesn't know or care what is responsible for changing it). As the documentation for this event indicates:
User input or setting the Text property to a new value raises the TextChanged event.
If you need to run custom validation logic when you add text to your textbox in code, you will need to invoke whatever method contains the validation logic yourself. Extract it into a separate method, which you call from the Validating/Validated event handler and from all of the places in your code where you set the textbox's Text property.
As a supplement to the other answers that have already been posted, I strongly recommend using either the Validating (if you want to be able to cancel the validation) or Validated events to handle the textbox losing focus, rather than the somewhat more obviously named LostFocus event.
You can use the LostFocus or Validated events.
Use a member variable.
private bool _changeByCode;
public void DoSomeChanges()
{
_changeByCode = true;
textbox1.Text = "Hello";
_changeByCode = false;
}
public void Textbox1_Change(object source, EventArgs e)
{
if (_changeByCode)
return;
//do your validation here.
}
Is it possible to know if any of the textbox values have changed in the application.
I have around 30 textboxes and I want to run a part of code only if, any of the textboxes value has changed out of the 30. Is there a way I can know that.
Each text box will raise an event TextChanged when it's contents have changed. However, that requires you to subscribe to each and every event.
The good news is that you can subscribe to the event with the same method multiple times. The handler has a parameter sender which you can use to determine which of your 30 text boxes has actually raised the event.
You can also use the GotFocus and LostFocus events to keep track of actual changes. You would need to store the original value on GotFocus and then compare to the current value on LostFocus. This gets round the problem of two TextChanged events cancelling each other out.
You can assign an event handler to each of the TextBox's TextChanged events. All of them can be assigned to the same event handler in code. Then you'll know when the text changes. You can set a boolean flag field in your class to record that a change occurred.
This is perhaps on the rough and ready side, but I did it this way.
In the constructor, I created
bool bChanged = false;
In the TextChanged event handler of each control (actually same for each), I put
bChanged = true;
When appropriate, I could do some processing, and set bChanged back to false.
You can also just do this:
In your Constructor:
MyTextBox.TextChanged += new TextChangedEventHandler( TextChanged );
And Then this Method:
private void TextChanged(object Sender, TextChangedEventArgs e){
//Do something
}
try this. Add this code to the load/constructor. no need to specify the event in the XAML explicitly
this.AddHandler(TextBox.TextChangedEvent, new TextChangedEventHandler(TextChanged));
private void TextChanged(object Sender, TextChangedEventArgs e)
{
//ToDO (use sender to identify the actuale text from where it fired }
}