Postback From Controls inside Composite Web Control - asp.net

Let's say we have a composite web control with a combobox and a textbox. Is it possible to build into the control functionality such that when the text in the textbox changes, it posts back and adds the value as an option in the combobox?
I know that I could add an "onchange" handler to the textbox and make something work with Javascript, but that's not really what I'm looking to do. Is there a way to just put like:
Protected Sub txt1_TextChanged(sender As Object, e As System.EventArgs) Handles txt1.TextChanged
combo1.items.add(txt1.Text)
End Sub
in the web control code and it connect to the TextChanged event of the textbox?

In short yes, you should be able to do this.
I don't know what syntax you need for VB, but I have done similar things multiple times in C#. For C# you would add the name of the even handler to the markup of your text box, and set auto postback on the text box to true. Then the code behind event handler does what ever work you need it to.
As a rule I also define a custom event on the web control, and have the event handler for the textbox raise this custome event as well. This gives the option of letting the page that is using the control act on the event as well.
EDIT:
Here is an example with a DropDownList, it was part of a control to look up users within a set of Active Directory domains. If the user changed what domain they had selected we wanted it to search for the previously entered values on the new domain.
Mark-up:
<asp:DropDownList ID="ddl_Domain" runat="server" onselectedindexchanged="ddl_Domain_SelectedIndexChanged" AutoPostBack="True"></asp:DropDownList>
Code behind:
protected void ddl_Domain_SelectedIndexChanged(object sender, EventArgs e)
{
if (UserID != "" || LastName != "" || FirstName != "" || EmailAddress != "")
{
lnk_Find_Click(sender, e);
}
}
Or in the case where I have added a child control dynamically through code I have used this syntax:
DropDownList ddl = new DropDownList();
ddl.ID = "ddl";
ddl.DataTextField = "Text";
ddl.DataValueField = "Value";
ddl.SelectedIndexChanged += This_SelectedValue_Changed;
ddl.AutoPostBack = true;
As I said, I am not sure how to make this work with the Handles syntax of VB but it should be possible.

Related

Asp.net Dynamic controls dropdownlist and textbox prob

I
have created 2 drop down list and 2 text boxes dynamically in asp.net .i disable text box at run time .i want that when i select item from drop down text box should be enable how to perform this task please help me :(
On SelectedIndexChanged on the dropDownList call a function that sets the textbox enabled = true. To access controls that have been dynamically added you can use FindControl as per C#, FindControl
I think something like this should help you:
In your page's OnInit event:
DropDownList ddl = new DropDownList();
ddl.SelectedIndexChanged += new EventHandler(ddl_SelectedIndexChanged);
placeholder.Controls.Add(ddl); //assuming this is what you use to dynamically show the dropdown list
TextBox yourTextbox = new TextBox(); //declare the variable outside to be able to be accessed by other methods, but it must be instantiated here. declaration here is for illustration purposes only
yourTextBox.Enabled = false;
placeholder.Controls.Add(yourTextBox);
Inside the instantiated event handler:
void ddl_SelectedIndexChanged(object sender, EventArgs e)
{
yourTextbox.Enabled = true;
}

character encoding with asp.net dynamic textbox

Environment: .net 3.5, c#, sharepoint 2010
Existing functionality: I have a user control with a search text box and search button. When the submit button is hit, along with search results, a querystring with search keyword is built. On postback, the textbox is again populated with the search keyword from querystring. This works good.
Issue: Need to fix cross side scripting. so did a html.encode and again a filter to escape single quote with &amp#39; for the textbox value. but the textbox displays value as it is like "'searchingstring'".
I need to show the user only "Searchstring", but the value in the sourcecode should be &amp#39;searchingstring&amp#39; to prevent cross side script vulnerability.
(Note: Above text "&amp" is actually "&". not &amp#39. Since stackoverflow editor transforms it to single quotes, i replaced it with &amp for reading)
If i tried building the textbox dynamically on pageinit using stringbuilder, I am getting what i needed as i mentioned above.
eg:
StringBuilder sb = new StringBuilder();
if (Request.QueryString["str"] != null)
{
string strName = Request.QueryString["str"].ToString();
str_value = htmlCheckReturnData(strName ); //encoded string
sb.Append("<INPUT type='TEXT' runat = 'server' id = 'mystring' value = '" + str_value + "' />");
// Response.Write(sb.ToString());
}
else
{
sb.Append("<INPUT type='TEXT' runat = 'server' id = 'mystring' value = '' />");
}
ltlSearch.Text = sb.ToString();
But I need to check the value of the "mystring" text box inside pageload like,
if (!IsPostBack && !Page.IsAsync)
{
if (!string.IsNullOrEmpty(mystring.Value)) //NOT WORKING HOW TO GET the textbox value
{
//do something
}
}
Note: If I create the textbox control on page_init without a stringbuilder write method, the character with encoding displays on the textbox.
Any help?
Thanks
Venkat
Appending a string in your html, with runat="server" does not make it a server control. You will have to add your control dynamically from code behind, in page_init like this:
Add a PlaceHolder control:
<asp:PlaceHolder runat="server" ID="myPlaceHolder">
</asp:PlaceHolder>
Then this code in your Page_Init event to create the TextBox control:
protected void Page_Init(object sender, EventArgs e)
{
TextBox txt = new TextBox();
txt.ID = "myTxt";
myPlaceHolder.Controls.Add(txt);
}
To get the Control from the Page_Load event:
TextBox txt = (TextBox)myPlaceHolder.FindControl("myTxt");
now you can access the Text property like you would with any other control:
txt.Text
Couple of things. Adding controls dynamically could be sometimes a painfully experience. Asp.net is not handling this control's viewstate right now. So you might receive some errors depending on what you are trying to accomplish. There are tons of tutorials online that will help you in this process.
Dynamically Create Controls in ASP.NET with Visual Basic .NET
TRULY UNDERSTANDING DYNAMIC CONTROLS (PART 1)
Add Controls to an ASP.NET Web Page Programmatically

hyperlink in gridview

I have a hyperlink in a gridview which I want users to click on and it directs them to a particular page and also either passes in the first field of the gridview (the ID) or holds it in session, preferebly in session.
The link is just static text so no matter what record they click on i want to get them to the same page, but with that records ID available.
Just not sure how to add this to the NavigateUrl of the hyperlink.
ANy hints appreciated, thanks
You can easily generate the URL in the markup of your GridView without resorting to code. What you need to do is:
In the DataNavigateUrlFields
property of your HyperLinkField, put
the name of the column that contains
your id.
In the
DataNavigateUrlFormatString, put the
path to your page, plus the
querystring that the next page will
use to get the id, but where the
value should go, put {0} instead.
e.g.
<asp:Hyperlink DataNavigateUrlFields="ProductId" DataNavigateUrlFormatString="details.aspx?id={0} />
When the control is rendered at runtime, you will find that for each row, the {0} is replaced by the value of the ProductId column.
See String.Format and DataNavigateUrlFormatString for more details.
You can handle the Row_DataBound event to find the hyperlink control and update the NavigateUrl property.
You can add simple html control Text to link, it will produce same html.
Use HyperLink control and then write an event handler function for RowDataBound event, like this:
protected void OnRowDataBound(object source, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
HyperLink hyperLink = e.Row.FindControl("hyperLinkID") as HyperLink;
// example, adjust this to your needs.
hyperLink.NavigateUrl = "~/detail.aspx?id=" + DataBinder.Eval(e.Row.DataItem, "ID");
}
}
Not sure why you have taken server control instead of tag of HTML.
two ways you can do it.
1)if it is an static link just prefix the page name and append the id in mark up.
for ex
<a href='myPage.aspx<%#Eval("YourID")%>'><strong>Click me to navigate</strong></a>
2)give some id to the a tag and make it runat server handle the data bound event and bind the value to it.
protected void MyGridview_ItemDataBound(object sender, ListViewItemEventArgs e)
{
HtmlAnchor AncImage = e.Item.FindControl("AncImage") as HtmlAnchor;
AncImage.href="myPage.aspx"/id=" + DataBinder.Eval(e.Row.DataItem, "ID"); ;
//the id is the value that you want to append for redirection
}

ASP.NET WebControl & Page - Adding controls (like TextBox) dynamically

I'm trying to create a custom server control (WebControl) with a text box.
I add asp.net textbox to the custom control in CreateChildControls override. In OnInit override I add event handler to TextBox.TextChanged.
Everything works, except that TextChanged never fires. I looked at viewstate and it looks like my textbox never saves its Text property in the viewstate. I've tried to set Text in various places, including constructor, but nothing works.
How can I get TextBox dynamically added to WebControl to save it's Text in viewstate and get TextChanged event to fire?
I would greatly appreciate an example of WebControl code behind with TextBox being added dynamically and TextChanged event being fired.
The dynamically created control must be created again in each post back, (the pageInit event is the better option) for the event to be fired.
BTW, if you want the TextChanged event to generate a postback you must also set the AutoPostback of the control to true.
fixed it. dynamic control must be created and added in Init event. It must be assigned an ID without special ASP.NET symbols ('$' or ':' inside custom ID will break things). All properties must be assigned after control is added to the controls tree.
here's a working example for Page codebehind:
private readonly TextBox _textBoxTest = new TextBox();
protected void Page_Init( object sender, EventArgs e )
{
this.form1.Controls.Add( _textBoxTest );
_textBoxTest.Text = "TestBoxTest";
_textBoxTest.ID = "TestBoxTestId";
_textBoxTest.TextChanged += this._textBoxTest_TextChanged;
}
void _textBoxTest_TextChanged( object sender, EventArgs e )
{
_textBoxTest.Text = "Worked";
}
for WebControl place init code in OnInit override
This will help you out. In short, you need to handle the viewstate for your Dynamically added control on your own.

Dynamically add CalendarExtender to Textbox subclass server control?

I'm trying to create a server control, which inherits from TextBox, that will automatically have a CalendarExtender attached to it. Is it possible to do this, or does my new control need to inherit from CompositeControl instead? I've tried the former, but I'm not clear during which part of the control lifecycle I should create the new instance of the CalendarExtender, and what controls collection I should add it to. I don't seem to be able to add it to the Page or Form's controls collection, and if I add it to the (TextBox) control's collection, I get none of the pop-up calendar functionality.
I accomplished this in a project a while back. To do it I created a CompositeControl that contains both the TextBox and the CalendarExtender.
In the CreateChildControls method of the CompositeControl I use code similar to this:
TextBox textbox = new TextBox();
textbox.ID = this.ID + "Textbox";
textbox.Text = this.EditableField.TextValue;
textbox.TextChanged += new EventHandler(HandleTextboxTextChanged);
textbox.Width = new Unit(100, UnitType.Pixel);
CalendarExtender calExender = new CalendarExtender();
calExender.PopupButtonID = "Image1";
calExender.TargetControlID = textbox.ID;
this.Controls.Add(textbox);
this.Controls.Add(calExender);
Of course make sure that the form containing this CompositeControl has a toolkit script manager.
I know this is an old thread, but I came across it when I had a similar question. This is what I ended up implementing, and it works great. If you want the control to BE a TextBox, then simply pump out the extender during the call to Render.
Imports System.Web.UI.WebControls
Imports AjaxControlToolkit
Public Class DateTextBox
Inherits TextBox
Private _dateValidator As CompareValidator
Private _calendarExtender As CalendarExtender
Protected Overrides Sub OnInit(ByVal e As System.EventArgs)
MyBase.OnInit(e)
_dateValidator = New CompareValidator
With _dateValidator
.ControlToValidate = ID
Rem set your other properties
End With
Controls.Add(_dateValidator)
_calendarExtender = New CalendarExtender
With _calendarExtender
.TargetControlID = ID
End With
Controls.Add(_calendarExtender)
End Sub
Protected Overrides Sub Render(ByVal writer As System.Web.UI.HtmlTextWriter)
MyBase.Render(writer)
_dateValidator.RenderControl(writer)
_calendarExtender.RenderControl(writer)
End Sub
End Class
You can easily add ajax calendar in custom server controls. You need to add two reference in your application.
1. AjaxControlToolkit.dll
2. System.Web.Extensions
With the help of second reference we will get all the property of “CalendarExtender” in your custom server controls.
When you are trying to not allow users to type anything in the textbox, but only be filled by the calendar extender and then you try to get the selected date from the textbox control it may be empty string if you have set the textbox property to ReadOnly="True".
Its because read only controls are NOT posted back to the server. Workaround for this is the following:
protected void Page_Load(object sender, EventArgs e)
{
TextBox1.Attributes.Add("readonly", "readonly");
}
Hope it helps.

Resources