I am working in VS10 using C# in ASP.NET. In my design form, I have a textArea(standard HTML control).
<textarea id="Text1" rows = "8"; cols="30" onkeyup="AutoGrowTextArea(this)" name="S1"> </textarea>
Now in my code-behind page, I am using C# to code the controls. I have given the textArea an auto-expand functionality which I require thru out my project. I need this TextArea as a server control, like when we put a textBox in the design page, we can use it in the code-behind page to code, since it is a server control. However, textArea isn't a server control.
I have gone thru the previous posts on the site but i did not get anything enough useful.
I have even tried using [<% %>] system, and [runat="server"] but it did not help.
What i wanna do is to use the textArea in the Code-behind page, i.e. call it in the coding space, just like we can call the TextBox control objects.
So, can anyone please help me with this,,,
Regards..
javascript for autogrowing text box is:
<script type="text/javascript">
function AutoGrowTextArea(textField)
{
if (textField.clientHeight < textField.scrollHeight)
{
textField.style.height = textField.scrollHeight + "px";
if (textField.clientHeight < textField.scrollHeight)
{
textField.style.height = (textField.scrollHeight * 2 - textField.clientHeight) + "px";
}
}
}
</script>
Try this
add runat="server" to the tag
<textarea id="Text1" runat="server" rows = "8" cols="30" onkeyup="AutoGrowTextArea(this)" name="S1"> </textarea>
you can manipulate raw html controls setting the runat="server" propery of the control.
<textarea id="Text1" runat="server" rows = "8"; cols="30" onkeyup="AutoGrowTextArea(this)" name="S1"> </textarea>
You can add runat="server" in your markup and it will be a server control.
You can also create server controls in your code behind. Declaration (In Visual Basic):
Protected WithEvents foo As Global.System.Web.UI.HtmlControls.HtmlGenericControl = Global.System.Web.UI.HtmlControls.HtmlGenericControl("textarea")
If you want to use something in all your project, you can declare a class inherited from Control or HtmlGenericControl and you can implement whatever you need to implement everywhere where you your new control.
<asp:TextBox id="thisIsMyTextBox" runat="server" multiline="true" width="200px" onkeyup="AutoGrowTextArea(this)" height="80px" style="resize:none;"></asp:TextBox>
You can play with the width/height as you wish !
function AutoGrowTextArea(textField)
{
if(textField.Lenght()%50==0)//50 is the number of character in your textbox
{
if (textField.clientHeight < textField.scrollHeight)
{
textField.style.height = textField.scrollHeight + "px";
if (textField.clientHeight < textField.scrollHeight)
{
textField.style.height = (textField.scrollHeight * 2 - textField.clientHeight) + "px";
}
}
}
Related
I've struggled with this for days now, trying to access html inputs, i.e. checkboxes or textboxex generated at runtime based on DB results. My HTML which is added as a literal control to a asp placeholder looks like this:
<div class='cart-item'>
<div class='product-name'> <h3>gold baseball figure</h3></div>
<img src='Graphics/gold-trophy.png'></img>
<div class='inventory-short-description'> <p>A finely crafted gold plated baseball figuring to top your choice of trophey base (sold seperatly).</p></div>
<div class='clear'></div>
<div class='item-price'><p>$22.95</p></div>
<div class='cart-item-checkbox'><label><input type='checkbox' id='1' name='1' runat='server'/> Select </label>
<a href='products.aspx?viewItem=1'>view item </a></div></div
Question is, how do I access this check box in the .cs code behind page?
My code which is generating this html and adding it to the page is in the overrided OnInit method. Looking at the placeholder on postback shows that the checkbox is in the literal control.
I've tried:
Page.FindControl() returns null when searching for dynamic control
ASP.NET page_init event?
FindControl() return null
http://forums.asp.net/t/1336244.aspx?finding+HTML+control
....And countless others.
Yesterday I used a hackish way to set the value of these checkboxes to a asp.net hidden field using jquery. My coworkers (all java devs) say this seems to be the wrong way to access these elements. Is there a better way? I'm beginning to think I've coded myself into a spot I can't get out of.
Thanks for the help.
In your .aspx
<asp:Repeater ID="rptItems" runat="server" EnableViewState="False">
<ItemTemplate>
<asp:TextBox ID="txtName" runat="server" />
</ItemTemplate>
</asp:Repeater>
In your .aspx.cs file you can access repeater in postback events as below
foreach (RepeaterItem rptItem in rptItems.Items)
{
TextBox txtName = (TextBox)rptItem.FindControl("txtName");
if (txtName != null) { System.Diagnostics.Debug.Write(txtName.Text); }
}
I have a division something like :
<div id="divAdditionalInfo" runat="server">
//html code here
</div>
In code behind, I need to prompt out a small window (generate by this div) more than 1 time.
Because it is the same div, so I only can see the final time window pop up.
My main question is, Can I change the div id in code behind?
and then use the div id to pop up another window.
Something like :
divAdditionalInfo.Style["visibility"] = "visible";
divAdditionalInfo.Style["display"] = "table-cell";
After change :
divAdditionalInfo.ID = "div2";
But I cant write code like :
div2.Style["visibility"] = "visible";
I only can write back :
divAdditionalInfo.Style["visibility"] = "visible";
There is find control method for panel, text box, button and so on, but how about division?
Can find control division?
something like :
Division d = (Division).FindControl("div2"); //find control on the div id that just change
d.Style["visibility"] = "visible";
kindly comment my question is not clear : )
I have tried something like this.
aspx file:
<div id="div1" runat="server">
<asp:Label ID="lbl1" runat="server" Text="Div ID: "></asp:Label>
</div>
<asp:Button ID="btn_change" runat="server" Text="Change" OnClick="btn_change_Click" />
On button Click event:
div1.ID = "div2";
lbl1.Text = lbl1.Text + div1.ID.ToString();
It will change the ID of div for the temporary. Button when you refresh the page it will automatically get the ID which you have specified on ASPX page.
I think this will work when the ID is chenged by you at that time you can perform the operations you want to perform.
You will able to find Div Tag in FindControl() of panel or form but in Code behind You will not have the Division Control or something like that. Because it not the Asp.Net control it is typical HTML control.
This is question is in relation to my last question in case you want some more background information.
My question is: Is it possible to make a cell in an asp.net Table clickable?
Or Is it at least possible to make a clickable WebControl (which should be possible to place in a ControlCollection), that is not a Button or a LinkButton, in ASP.NET?
And if not, is it possible to multiple lines of information into the button text?
I've tried adding other components to the button's ControlCollection (which I've seen working in the Windows Forms version of the Button), to see if I could render child components to a button, but without success:
private void ModifyTableCell(TableCell cell)
{
//Create new button
Button btnCell = new Button();
btnCell.Click += (sender, args) =>
{
//Event for the button
};
//Create new Label
Label lblCell = new Label();
lblCell.Font.Bold = true;
lblCell.Text = "This text won't appear";
btnCell.Controls.Add(lblCell); //Attempt to add label to Button
cell.Controls.Add(btnCell);
}
EDIT: I ended up just creating a multi-lined LinkButton for the entire cell.
You should be able to make pretty much any control clickable by assigning an onclick attribute and leveraging the __doPostBack function.
ctrl.Attributes["onclick"] = string.Format("__doPostBack('{0}', '{1}');", ctrl.ClientID, "SomeArgument");
You could also use the GetPostBackEventReference method too. This option is actually safer, because it will register the __doPostBack function it doesn't already exist:
ctrl.Attributes["onclick"] = Page.ClientScript.GetPostBackEventReference(ctrl, string.Empty);
Then, in the code-behind you can simply override the RaisePostBackEvent method:
protected override void RaisePostBackEvent(IPostBackEventHandler source, string eventArgument)
{
base.RaisePostBackEvent(source, eventArgument);
if (eventArgument == "SomeArgument") //using the argument
{
//do whatever
}
}
You can add multiple lines to a asp.net button by using the string builder, something like:
System.Text.StringBuilder buttonText = new System.Text.StringBuilder();
buttonText.AppendLine("first line");
buttonText.AppendLine("second line");
btnMultiline.Text = buttonText.ToString;
I am not sure how you imagine such a composite control would be rendered. Remember that each ASP.NET control in the end outputs HTML. You Button essentially outputs a
<input type="button">The button text</input>
If you want to place anything else inside the <input> tag, it must be HTML-compatible. I'm not sure the input tag allows other HTML inside.
If it is a LinkButton on the other hand, the generated HTML markup is an <a href=""> tag. You can put anything there, even an image if you wish, which will become clickable.
I am not sure what is your full scenario, but what you're trying to do smells bad. I suggest that you either use a LinkButton or rethink your approach, just have in mind what the final output in HTML would be.
In reading both of your posts, it looks like you want to be able to click on anything in the cell and have it post back as if the whole cell were a button?
If so, one of the fairly simple ways to do it is to build your cell content as you would if you were not trying to post back. Then add a button with a style of display:none;. You can then use client side scripting to capture the click event of the cell, and raise the click event of the button to cause a post back.
This allows you to create the cell content in any way you like, and the postback code and handlers are automatically generated for you.
Using JQuery you end up with something along the lines of this:
<head runat="server">
<style>
input.ClickableCellButton
{
display: none;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.7.1.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
$("td.ClickableCell").click(function (event) { $(event.target).children("input.ClickableCellButton").click() });
});
</script>
<div>
<table>
<tbody>
<tr>
<td class="ClickableCell">
Cell Contents<br />
on multiple lines
<asp:Button ID="Button1" runat="server" Text="Button" CssClass="ClickableCellButton"
OnClick="Button1_Click" />
</td>
</tr>
</tbody>
</table>
</div>
</form>
</body>
And if not, is it possible to multiple lines of information into the
button text?
For this particular case, you can accomplish this via CSS only; no need to extend Button:
<asp:button id="myMultilineButton" runat="server" style="width:60px; white-space: normal;" Text="Several lines of text" />
It will render as:
I building an online CV application that allows the user to add new education sections that consist of a number of text boxes and labels.
What is the best way of dynamically creating the form elements and reading them depending on whether the user hits an [Add another] button.
1) server side :In your asp.net button click event , Create the required controls (text box, drop down etc..) dynamically and add that to a conainer like a Panel.
2)Client Side : Using javascript create elements and append to an existing container (div). In this approach, you save a server round trip because you are doing it in the client side.
Here is a javascript sample using jquery which will give you an idea.
HTML
<div id="divContainer">
Education 1 <input id="txt1" type="text" class="txtBox"/>
</div>
<input id="btn1" type="button" value="Add Another" />
Javascript
var counter=1;
$("#btn1").click(function(){
counter++;
$("#divContainer").append("<br/> Education "+counter + " <input type='text' id='txt"+counter+"' class='txtBox' />");
});
Here is the working sample : http://jsfiddle.net/huYMT/13/
I don't know the best way unfortunately but I can tell you what I did in web forms when I used to use them.
I made a PlaceHolder where I could dump in controls on the fly type of thing. I made a UserControl that could be repeated again and again that had public properties. I wrapped an UpdatePanel around the PlaceHolder and attached a click event tied to the UpdatePanel so the user would have the AJAX experience.
Here is kind of a quick summarized version of the code. I can give you the full source if you want. Let me know.
<script runat="server">
void aspx_Init(object sender, EventArgs e)
{
AddCreditCardReceiptButton.Click += new EventHandler(AddCreditCardReceiptButton_Click);
}
void AddCreditCardReceipt()
{
AddCreditCardReceipt(this.ID + "_" + Guid.NewGuid().ToString("N").Substring(0, 5));
}
void AddCreditCardReceiptButton_Click(object sender, EventArgs e)
{
AddCreditCardReceipt();
CreditCardReceipt lastAdded = (CreditCardReceipt)CreditCardReceiptPH.Controls[CreditCardReceiptPH.Controls.Count - 1];
lastAdded.ContainerStyle = "display:none";
ScriptManager.RegisterStartupScript(lastAdded, typeof(CreditCardReceipt), lastAdded.ClientID,
"$('#CreditCardReceipt_" + lastAdded.ClientID + "').toggle(500);", true);
}
</script>
<asp:UpdatePanel runat="server" id="CreditCardReceiptUpdatePanel" UpdateMode="Conditional" ChildrenAsTriggers="true">
<ContentTemplate>
<asp:PlaceHolder ID="CreditCardReceiptPH" runat="server" />
<asp:Button runat="server" ID="AddCreditCardReceiptButton" CausesValidation="false" Text="(+) Add Credit Card Receipt" /></div>
</ContentTemplate>
I prefer to create a user control for education section.
And if you hit the add button, The click event of button could dynamic add a new user
control in UI.
I am developing a user control (ascx) in ASP.NET which uses javascript for manipulating controls. Currently the javascript code is inlined and uses <%= somecontrol.ClientID %> to get the control it needs.
I want to put the javascript file in external file but from external file I cannot use the above syntax for retrieving controls. I have read about possible solutions in this and this answers but the problem is that the user control can be placed multiple times on page. This means that the Controls array (mentioned in the answers) will be rendered several times with different items. As a result the script will not be able to retrieve the id it needs. If I put <%= ClientId %> in the name of array that holds items then I will have the same problem as I am trying to solve.
Any ideas?
Ok, a different approach, that I try to use a JavaScript-class style, and then initialize it for each control.
In the external javascript file, write your code as:
function oNameCls(ControlId1) {
this.ControlId1 = ControlId1;
this.DoYourWork1 = function() {
// use the control id.
// this.ControlId1
}
this.DoYourWork2 = function() {
// use the control id.
// this.ControlId1
}
}
And on the control do the call like that.
<script language="Javascript" type="text/javascript">
// init - create
var <%=this.ClientID%>MyCls = new oNameCls(<%=Control1.ClientID%>);
// do your work
<%=this.ClientID%>MyCls.DoYourWork1();
</script>
Hope now help better.
The way I solve this problem is to use CSS classes or place the controls within containers with known IDs and then traverse into the container's children to get the actual controls. For example:
<asp:TextBox ID="Something" runat="server" CssClass="mycontrol" ... />
Could be accessed via:
jQuery('.mycontrol');
Or:
<div id="ControlContainer">
<asp:TextBox ID="Something" runat="server" ... />
</div>
Could be accessed via:
jQuery("#ControlContainer input[type='text']");
The only real problem with this approach is you're tying your code to specific markup on the page, which can be a hassle if the markup changes a lot.
What about a hidden variable:
<input type="hidden" id="ClientId" value="<%=ClientId %>">
Then from your js:
$("#" + $("#ClientID").val())
Or, put the hash in:
<input type="hidden" id="ClientId" value="#<%=ClientId %>">
...
$($("#ClientID").val())
If you want to find a specific control when there could be multiple copies, this can't be done. How would the external javascript know which of the n controls you wanted?
How can rig the behavior up to a class and find the elements relative to the position of the action control, like this:
UserControl:
<div class="myControl">
<asp:Button id="MyButton" runat="server" Text="Click Me" />
<div style="display:none;">Show me!</div>
</div>
If you jQuery was written to be relative like this:
$(".myControl input").click(function() {
$(this).next().slideDown();
});
In this case, it doesn't matter what the specific IDs are, as long as you can navigate the DOM relatively to the controls you need. Even if it's more complex like .closest("div").next().find(".bob").prev()...whatever you need to get there works.