Prevent Multi-Line ASP:Textbox from trimming line feeds - c#

I have the following webform:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs"
Inherits="TestWebApp.Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:TextBox ID="txtMultiLine" runat="server"
Width="400px" Height="300px" TextMode="MultiLine"></asp:TextBox>
<br />
<asp:Button ID="btnSubmit" runat="server"
Text="Do A Postback" OnClick="btnSubmitClick" />
</div>
</form>
</body>
</html>
and each time I post-back the leading line feeds in the textbox are being removed. Is there any way that I can prevent this behavior?
I was thinking of creating a custom-control that inherited from the textbox but I wanted to get a sanity check here first.

I ended up doing the following in the btnSubmitClick()
public void btnSubmitClick(object sender, EventArgs e)
{
if (this.txtMultiLine.Text.StartsWith("\r\n"))
{
this.txtMultiLine.Text = "\r\n" + this.txtMultiLine.Text;
}
}
I must be really tired or sick or something.

I think that the problem here is in the way that the browser renders the textarea contents, not with ASP.NET per se. Doing this:
public void btnSubmitClick(object sender, EventArgs e) {
this.txtMultiLine.Text = "\r\n" + this.txtMultiLine.Text;
}
will let you reach the desired screen output, but you'll add an extra newline to the Text that the user didn't enter.
The ideal solution would be for the TextBox control in ASP.NET to always write the newline AFTER writing the open tag and BEFORE writing the contents of Text. This way, you'd reach the desired effect without trumping the contents of the textbox.
We could inherit from TextBox and fix this by overriding RenderBeginTag:
public override void RenderBeginTag(HtmlTextWriter writer) {
base.RenderBeginTag(writer);
if (this.TextMode == TextBoxMode.MultiLine) {
writer.Write("\r\n"); // or Environment.NewLine
}
}
Now, creating a new class for this small issue seems really overkill, so your pragmatic approach is completely acceptable. But, I'd change it to run in the PreRender event of the page, which is very late in the page lifecycle and would not interfere with the processing of the submitted text in the OnSubmit event of the button:
protected void Page_Load(object sender, EventArgs e) {
this.PreRender += Page_OnPreRender;
}
protected void Page_OnPreRender(object sender, EventArgs e) {
this.txtMultiLine.Text = "\r\n" + this.txtMultiLine.Text;
}

Related

Call code behind method from aspx

I have the following aspx code where I am calling a method from code behind. The result of the code behind method is not getting rendering in the page.
<%# Page Language="C#" AutoEventWireup="false" Src="LeftMenuSrce.aspx.cs" Inherits="LeftMenuSrce" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
<html>
<head>
<title>Home</title>
</head>
<body>
<asp:Table ID ="LeftMenuTable" runat="server">
<asp:TableRow>
<asp:TableCell ID="LeftMenuSrce" OnDataBinding="_getLeftMenuSrc"></asp:TableCell></asp:TableRow>
</asp:Table>
</body>
</html>
Below is my cs code:
public class LeftMenuSrce : System.Web.UI.Page
{
protected System.Web.UI.WebControls.TableCell LeftMenuSrce;
protected System.Web.UI.WebControls.Table LeftMenuTable;
protected void Page_Load(object sender, EventArgs e)
{
LeftMenuSrce.DataBind();
}
protected string _getLeftMenuSrc()
{
string leftMenu;
leftMenu = "LeftMenuNew.aspx";
return leftMenu;
}
}
Even I have tried div instead of asp:tables, but nothing was working.
<div>
<%#_getLeftMenuSrce()%>
</div>
Any clues to overcome this issue? Thanks in advance.
Please note I have referred below links, but nothing helped me.
How to call a code-behind method from aspx page?
Call code behind method from aspx page
ASP.NET - Use variable in .aspx page
Use <%=_getLeftMenuSrc() %>
You must implement your method "_getLeftMenuSrc()" as an event handler.
Example:
protected void _getLeftMenuSrc(object sender, EventArgs e) {}
I guess you simply try to write some text into your TableCell LeftMenuSrce.
One way to do this is writing a OnPreRender event handler like this:
protected void TableCell1_OnPreRender(object sender, EventArgs e)
{
TableCell1.Text = "My text in a cell !!";
// Hint: 'sender' is your table cell ;-)
((TableCell) sender).Text = "My other text in that cell !!";
}
An other way is to fill all your tables cells within the Page_Load event. Like this:
protected void Page_Load(object sender, EventArgs e)
{
TableCell1.Text = "My text in a cell !!";
}
BTW: Don't use tables to build a navigation ;-). Try this link: http://www.w3schools.com/css/css_navbar.asp

ASPX Postback selectedIndexChanged

I am using an combobox with some values and AutoPostBack = true, the page does not refresh.
I have a selectedIndexChanged event as well.
I managed to get the selectedValue and I would like to show this in a TextBox.
In the selectedIndexChanged event I did:
textBox1.Text = selectedValue.ToString();
When I inspect this textbox element with Google Chrome I can see the value is set in the TextBox.
But in the browser the value isn't shown, still an empty TextBox.
Do you guys have any clue why this could happen?
Thanks!
How do you populate items for ComboBox? If dynamically via On-Load event then make sure that method that adds items does not run on PostBack.
Here is your working code buddy.
Don't forget ToString method.
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Test2.aspx.cs" Inherits="Test2" %>
<%# Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="asp" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server"></asp:ToolkitScriptManager>
<asp:ComboBox ID="ComboBox1" runat="server" AutoPostBack="True" OnSelectedIndexChanged="ComboBox1_SelectedIndexChanged">
<asp:ListItem>Item1</asp:ListItem>
<asp:ListItem>Item2</asp:ListItem>
<asp:ListItem>Item3</asp:ListItem>
</asp:ComboBox>
<asp:TextBox runat="server" ID="textBox1"/>
</div>
</form>
</body>
</html>
and code
public partial class Test2 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void ComboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
textBox1.Text = ComboBox1.SelectedValue.ToString();
}
}

Update Main page from user control

I have a grid view in my main page and I display some data for user(using BindGrid method).this grid view has some command buttons for each row that perform some operation like Update. when user clicks on update button I show to him/her a user control to update values.and when user clicks on update I want grid bind to new data(I want call BindGrid for new data). How I can do this and call a method in main page from user control?
Edit 1)
I wrote this code for user control:
public partial class SomeUserControl : System.Web.UI.UserControl
{
public event EventHandler StatusUpdated;
private void FunctionThatRaisesEvent()
{
if (this.StatusUpdated != null)
this.StatusUpdated(new object(), new EventArgs());
}
public void Page_Load(object sender, EventArgs e)
{
//....
}
protected void Button1_Click(object sender, EventArgs e)
{
FunctionThatRaisesEvent();
}
}
and the designer for user control :
<%# Control Language="C#" AutoEventWireup="true" CodeFile="SomeUserControl.ascx.cs" Inherits="SomeUserControl" %>
<asp:Button ID="Button1" runat="server" Text="Update" Height="70px"
onclick="Button1_Click" Width="183px" />
and add this code for main page:
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Unnamed1_Click(object sender, EventArgs e)
{
SomeUserControl userControl = (SomeUserControl)LoadControl("SomeUserControl.ascx");
userControl.StatusUpdated += new EventHandler(userControl_StatusUpdated);
Panel1.Controls.Add(userControl);
}
void userControl_StatusUpdated(object sender, EventArgs e)
{
GetDate();
}
private void GetDate()
{
TextBox1.Text = DateTime.Today.ToString();
}
and designer for main page:
<%# Register src="SomeUserControl.ascx" tagname="SomeUserControl" tagprefix="uc1" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<div>
<asp:UpdatePanel ID="upd1" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:Button runat="server" Text="Add User Control" Height="44px" ID="Nims"
onclick="Unnamed1_Click" Width="133px" />
<asp:Panel ID="Panel1" runat="server" BackColor="#FFFFCC"></asp:Panel>
</ContentTemplate>
</asp:UpdatePanel>
</div>
</form>
</body>
</html>
but it does not work and nothing happend. even I add break point for click user control button code but it seems that event not raise.
Raise the event from the user control, and handle the event from the main page. Check out this question.
//** EDIT **//
You are adding the user control dynamically on button click. When you click the button on your user control it first will initiate postback on the main page - now your user control no longer exists (which is why the event is not raised). If you change your main page designer to look like this:
<%# Register Src="SomeUserControl.ascx" tagname="SomeUserControl" tagprefix="uc1" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<div>
<asp:UpdatePanel ID="upd1" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:Button runat="server" Text="Add User Control" Height="44px" ID="Nims"
onclick="Unnamed1_Click" Width="133px" />
<asp:Panel ID="Panel1" runat="server" BackColor="#FFFFCC">
<uc1:SomeUserControl ID="userControl" runat="server" />
</asp:Panel>
</ContentTemplate>
</asp:UpdatePanel>
</div>
</form>
and your code-behind to look like this
protected void Page_Load(object sender, EventArgs e)
{
userControl.StatusUpdated += new EventHandler(userControl_StatusUpdated);
}
void userControl_StatusUpdated(object sender, EventArgs e)
{
GetDate();
}
private void GetDate()
{
TextBox1.Text = DateTime.Today.ToString();
}
you will see what I mean. Try setting breakpoints on the page load events of your main page and your user control to see exactly the order in which things happen.
You can register an event in your user control, raise the event when user clicks on update button and capture that event on the page.
http://codebetter.com/brendantompkins/2004/10/06/easily-raise-events-from-asp-net-ascx-user-controls/
you need to use event handler for that
define event handler in your ascx page
public event EventHandler ButtonClickDemo;
when you are performing update or delete event use following code there for event handler.
ButtonClickDemo(sender, e);
in parent page use following
protected void Page_Load(object sender, EventArgs e)
{
btnDemno.ButtonClickDemo += new EventHandler(btn_Click);
}
the function to bind grid of parent page
protected void btn_Click(object sender, EventArgs e)
{
BindGrid();
}
above code will call BindGrid function of parent page.

Ext.Net Button Event not firing

I am using Ext.Net and I have a problem.
I am creating dynamic buttons. It is working but if i click, the button event is not working.:(
How can I fix it?
My code:
foreach (var events in eventsInformation)
{
Ext.Net.Button btn = new Ext.Net.Button();
btn.ID = events.EvtId.ToString();
btn.Text = events.EvtName;
btn.Click += new EventHandler(Tickets_click);
ViewPort1.Controls.Add(btn);
}
There are a couple things that require correction in the original sample:
By default, Ext.NET Button Components do not AutoPostBack (ie, reload the entire page). It is encouraged to use DirectEvents (Ajax call) if you want to communicate with the server and avoid a complete page reload.
Ext.NET Components should be added to the parent .Items Collection, instead of the .Controls Collection.
Here's a complete demo with both these corrections.
Example
<%# Page Language="C#" %>
<%# Register assembly="Ext.Net" namespace="Ext.Net" tagprefix="ext" %>
<script runat="server">
protected override void OnInit(EventArgs e)
{
Ext.Net.Button btn = new Ext.Net.Button();
btn.Text = "Submit (AutoPostBack)";
btn.Click += Button1_Click;
// 1. Set to AutoPostBack, default is "false"
btn.AutoPostBack = true;
// 2. Add Button to .Items Collection
this.ViewPort1.Items.Add(btn);
base.OnInit(e);
}
protected void Button1_Click(object sender, EventArgs e)
{
X.Msg.Notify("Server Time", DateTime.Now.ToLongTimeString()).Show();
}
</script>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Ext.NET Example</title>
</head>
<body>
<form runat="server">
<ext:ResourceManager runat="server" />
<ext:Viewport ID="ViewPort1" runat="server" />
</form>
</body>
</html>
Now, I'd recommend changing your AutoPostBack Button Click event to a DirectEvent Click. That would require making the following three revisions to the code-behind.
Example
<script runat="server">
protected override void OnInit(EventArgs e)
{
Ext.Net.Button btn = new Ext.Net.Button();
btn.Text = "Submit (DirectEvent)";
// 2. CHANGE to .DirectClick
btn.DirectClick += Button1_Click;
// 3. REMOVE btn.AutoPostBack = true;
this.ViewPort1.Items.Add(btn);
base.OnInit(e);
}
// 3. CHANGE "EventArgs" to "DirectEventArgs"
protected void Button1_Click(object sender, DirectEventArgs e)
{
X.Msg.Notify("Server Time", DateTime.Now.ToLongTimeString()).Show();
}
</script>
Hope this helps.
Use Ext.net DirectMethod instead of ASP.NET postback event handler.
<ext:Button ID="Button1" runat="server" Text="Click Me" Icon="Lightning">
<Listeners>
<Click Handler="Ext.net.DirectMethods.SetTimeStamp();" />
</Listeners>
</ext:Button>
<script runat="server">
[DirectMethod]
public void SetTimeStamp()
{
this.Label1.Text = string.Concat("Server Time: ", DateTime.Now.ToLongTimeString());
}
The place to start is the ASP.NET Page Life Cycle Overview. If you're programatically adding controls to an asp.net page then you should familiarise yourself with it, if you're not already =)
Now work your way down this checklist:
Are you always adding the components (buttons in this instance) to the page? If you don't add them *always, then on post-back they won't be there for the EventHandler to be wired up to, for the handler to fire. (This may not apply to an Ext.Net button triggered by a DirectEvent, but it can't hurt).
Do you have the "usual" Ext.Net handler/module registrations in your web.config file to enable the direct events to be handled?
Have you verified that you're not receiving any javascript client-side errors that are inhibiting the event handler?
Use something like Fiddler to verify that the event is actually triggering a DirectEvent back to the server.
<ext:Button ID="extBtn1" runat="server" Text="Cancel">
<DirectEvents>
<Click OnEvent="extBtn1Click">
<EventMask ShowMask="true" />
</Click>
</DirectEvents>
</ext:Button>
This extBtn1Click event will fire in server-side.
The button is not present when Event is fired. That is why it doesnt work. If you construct some testing button in aspx file, it would work just fine.
Solution: You must construct the button during OnInit event so it will be present, and bound to EventHandler, during the new page cycle after clicking the button.

Programmatically Adding User Controls Inside An UpdatePanel

I'm having trouble dynamically adding controls inside an update panel with partial postbacks. I've read many articles on dynamic controls and I understand how to add and maintain them with postbacks but most of that information doesn't apply and won't work for partial postbacks. I can't find any useful information about adding and maintaining them with UpdatePanels. I'd like to do this without creating a web service if it's possible. Does anyone have any ideas or references to some helpful information?
This is, I think, one of the common pitfalls for asp.net programmers but isn't actually that hard to get it right when you know what is going on (always remember your viewstate!).
the following piece of code explains how things can be done. It's a simple page where a user can click on a menu which will trigger an action that will add a user control to the page inside the updatepanel.
(This code is borrowed from here, and has lots more of information concerning this topic)
<%# Page Language="C#" AutoEventWireup="true" CodeFile="SampleMenu1.aspx.cs" Inherits="SampleMenuPage1" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Sample Menu</title>
</head>
<body>
<form id="form1" runat="server">
<asp:Menu ID="Menu1" runat="server" OnMenuItemClick="Menu1_MenuItemClick">
<Items>
<asp:MenuItem Text="File">
<asp:MenuItem Text="Load Control1"></asp:MenuItem>
<asp:MenuItem Text="Load Control2"></asp:MenuItem>
<asp:MenuItem Text="Load Control3"></asp:MenuItem>
</asp:MenuItem>
</Items>
</asp:Menu>
<br />
<br />
<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="Menu1" />
</Triggers>
</asp:UpdatePanel>
</form>
</body>
</html>
and
using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class PlainSampleMenuPage : System.Web.UI.Page
{
private const string BASE_PATH = "~/DynamicControlLoading/";
private string LastLoadedControl
{
get
{
return ViewState["LastLoaded"] as string;
}
set
{
ViewState["LastLoaded"] = value;
}
}
private void LoadUserControl()
{
string controlPath = LastLoadedControl;
if (!string.IsNullOrEmpty(controlPath))
{
PlaceHolder1.Controls.Clear();
UserControl uc = (UserControl)LoadControl(controlPath);
PlaceHolder1.Controls.Add(uc);
}
}
protected void Page_Load(object sender, EventArgs e)
{
LoadUserControl();
}
protected void Menu1_MenuItemClick(object sender, MenuEventArgs e)
{
MenuItem menu = e.Item;
string controlPath = string.Empty;
switch (menu.Text)
{
case "Load Control2":
controlPath = BASE_PATH + "SampleControl2.ascx";
break;
case "Load Control3":
controlPath = BASE_PATH + "SampleControl3.ascx";
break;
default:
controlPath = BASE_PATH + "SampleControl1.ascx";
break;
}
LastLoadedControl = controlPath;
LoadUserControl();
}
}
for the code behind.
That's basically it. You can clearly see that the viewstate is being kept with LastLoadedControl while the controls themselves are dynamically added to the page (inside the updatePanel (actually inside the placeHolder inside the updatePanel) when the user clicks on a menu item, which will send an asynchronous postback to the server.
More information can also be found here:
http://aspnet.4guysfromrolla.com/articles/081402-1.aspx
http://aspnet.4guysfromrolla.com/articles/082102-1.aspx
and of course on the website that holds the example code I used here.
I encountered the problem that using the method mentioned above, LoadUserControl() is called twice when handling an event. I've read through some other articles and would like to show you my modification:
1) Use LoadViewstate instead of Page_Load to load the user control:
protected override void LoadViewState(object savedState)
{
base.LoadViewState(savedState);
if (!string.IsNullOrEmpty(CurrentUserControl))
LoadDataTypeEditorControl(CurrentUserControl, panelFVE);
}
2) Don't forget to set the control id when loading the usercontrol:
private void LoadDataTypeEditorControl(string userControlName, Control containerControl)
{
using (UserControl myControl = (UserControl) LoadControl(userControlName))
{
containerControl.Controls.Clear();
string userControlID = userControlName.Split('.')[0];
myControl.ID = userControlID.Replace("/", "").Replace("~", "");
containerControl.Controls.Add(myControl);
}
this.CurrentUserControl = userControlName;
}
Try this:
Literal literal = new Literal();
literal.Text = "<script type='text/javascript' src='http://www.googleadservices.com/pagead/conversion.js'>";
UpdatePanel1.ContentTemplateContainer.Controls.Add(literal);
You can replace the content of literal with any HTML content you want...

Categories