Cut Text to fit Textbox width and then right align - c#

I have several Textboxes in my Form which display filepaths. Mostly the filepaths are too long to display in the textbox. Is there a possibility to cut the surplus text and append some point characters to it and then align it right?
For example:
If the path is C:\Programs\anotherfolder\blabla\thisisatest.xml
A Textbox should show: ...lder\blabla\thisisatest.xml
If I resize the textbox, the text in it shall resize/expand with it.
Is there a way to do this automatically, maybe via Resize event of a textbox.
Thank you very much.

This might help if you are looking for resizing your textbox based on the text entered. You can call this code on any event like when you move focus out of textbox or after the data is loaded in the textbox. You need to replace your textbox's actual text in below line in the code.
mySize = e.Graphics.MeasureString("This is a test", myFont);

if this is a webpage ..
include 2 hidden variables as following
<div>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:HiddenField ID="HiddenField1" runat="server" />
<asp:HiddenField ID="HiddenField2" runat="server" />
</div>
include jquery and the script as following
<script type="text/javascript">
$(document).ready(function () {
$('#TextBox1').focus(function () {
$('#TextBox1').val($('#HiddenField1').val());
});
$('#TextBox1').blur(function () {
$('#TextBox1').val($('#HiddenField2').val());
});
});
</script>
set the fields in the code behind
string str = #"C:\Programs\anotherfolder\blabla\thisisatest.xml";
HiddenField1.Value = str;
if (str.Length > 10)
{
TextBox1.Text = "..." + str.Substring(str.Length - 10, 10);
HiddenField2.Value = TextBox1.Text;
}
This will show the whole string only when focused on the textbox.
Here is a demo of how it will look like.
Let me know if this was helpful or if you have any queries

Use this code to remove surplus text:
private string GetShortText(string longText)
{
int validTextSize = 27;
if (longText.Length <= validTextSize)
return longText;
return "..."+longText.Substring(longText.Length - validTextSize);
}
And use above code like this:
string longText = #"C:\Programs\anotherfolder\blabla\thisisatest.xml";
txtPath.Text=GetShortText(longText);
An for change alignment, if your form is a Windows Form you can use this code:
txtPath.TextAlign = HorizontalAlignment.Right;
Or if your form is a WPF form use this code:
txtPath.HorizontalContentAlignment = System.Windows.HorizontalAlignment.Right;

Related

Text cut in text area in ASP.net page

i'm trying to load text from database into many text fields
every thing is Ok , but one field of them text lenght is more than the length of the text field
so not all the text appear on the screen
that is my ASP.net code
<asp:TextBox ID="descriptiont" runat="server" Rows="3" Width="300px" Height="100px" Wrap="true">
and that is the code behind of it
descriptiont.Text = s.GetValue(1).ToString();
descriptiont.Enabled = false;
and that is what i get in the web page
the orginal text is "ECASTI (Egyptian Center for the Advancement of Science, Technology, and Innovation) "
can any one help ??!!!
use this:
<asp:TextBox id="TextArea1" TextMode="multiline" Columns="50" Rows="5" runat="server" />
Then you can access the content via:
string message= TextArea1.Text;
Dont fix the height of textbox. Height should be auto.And in css add property for textbox. It will work.
word-wrap: break-word;
Try this :
string s = "Your Text Field";
if (s.Length > 20)
{
//Change Width="450px"
}
Update :
You can aslo change width in CSS when text length is more than the length of the field.
Update 2 :
You can resize the textbox in C# with the following codes :
if (s.Length>20)
{
textBox1.TextChanged += textBox1_TextChanged;
}
void textBox1_TextChanged(object sender, EventArgs e)
{
Size size = TextRenderer.MeasureText(textBox1.Text, textBox1.Font);
textBox1.Width = size.Width;
}
Without changing the length of the textbox, may be it will mess up your design, add a textbox tool tip with the same content. So when you hover on textbox it will display the full content.
descriptiont.Text = s.GetValue(1).ToString();
descriptiont.Title = s.GetValue(1).ToString();
descriptiont.Enabled = false;
there is property of textbox named "TextMode". Please add 'TextMode="multiline"'
in your view or you can add it from your code behind file also.

How to assign dynamic placeholder to Textbox?

I know this question is asked before for assigning text to textbox, but they didn't have answers or the given answers didn't work for me. I have a static function for translations and I'm trying to use that to assign a placeholder to a Textbox. How can I do it in aspx page?
My code is:
<asp:TextBox ID="search" runat="server"
placeholder='<%# islem.DilGetir(7) %>'>
</asp:TextBox>
This one returns this sourcecode:
<input name="ctl00$search" type="text" id="ctl00_search">
You should set this attribute from the page code behind:
search.Attributes["placeholder"] = islem.DilGetir(7)
you can use ajax controll toolkit text box watermark I find it to be mnost usefull in aspx apps
http://www.asp.net/AjaxLibrary/AjaxControlToolkitSampleSite/TextBoxWatermark/TextBoxWatermark.aspx
<asp:TextBoxWatermarkExtender ID="TextBoxWatermarkExtender1" runat="server" TargetControlID ="search" WatermarkText="textthe my name" WatermarkCssClass="watermarked">
</asp:TextBoxWatermarkExtender>
on the back end
TextBoxWatermarkExtender1.WatermarkTex=islem.DilGetir(7);
I experienced the same problem. The exact solution: Take all placeholder's text to hiddenfield component(separated with , ) and with JS, take the inside array hiddenfield text and assign to input text's placeholder attr with jQuery or JS.
this code for multiselectbox choosen js and normal selectbox.
public void SelectFill(DataTable dtResult, HtmlSelect htmlSelect, string placeHolder, string textColumn, string valueColumn, string value)
{
htmlSelect.DataSource = dtResult;
htmlSelect.DataTextField = textColumn;
htmlSelect.DataValueField = valueColumn;
htmlSelect.DataBind();
bool isMultiple = false;
foreach (var item in htmlSelect.Attributes.Keys)
{
if (item.ToString() == "multiple")
{
isMultiple = true;
}
}
if (isMultiple)
{
htmlSelect.Attributes["data-placeholder"] = placeHolder;
}
else
{
ListItem placeHolderItem = new ListItem(placeHolder, "-1");//create placeholder option for non multible selectbox
placeHolderItem.Attributes.Add("disabled", "disabled");
htmlSelect.Items.Insert(0, placeHolderItem);
htmlSelect.Items[0].Selected = true;
}
}

Convert panel HTML to PDF using C# ASP.NET

I have a basic form with mostly textboxes and a few checkboxes and radio buttons. Pretty much when a user fills it out and hits submit, I need it to convert and display a PDF with the same structure and offer a print option. I have searched online and I have tried most of the options but nothing works.
I don't expect this to be too difficult, but I am fairly new to C# and can't figure out how to make an HTML panel into a PDF and print it. Any help would be appreciated, thanks in advance!
Here is the HTML for one of the labels and textboxes and the submit button:
<div>
<asp:Label ID="lblDate" runat="server" Text="Date:"></asp:Label>
<asp:TextBox ID="txtDate" runat="server"></asp:TextBox>
</div>
<asp:Button ID="SubmitButton" runat="server" Text="Button" OnClick="btnSubmit"/>
Once clicked, the .cs page will go through this:
litDate.Text = "Date: " + txtDate.Text + "<br />";
and update the panel to display the value:
<asp:Panel ID="PDFPanel" runat="server" Visible="false">
<asp:Literal ID="litDate" runat="server"></asp:Literal>
</asp:Panel>
I am not sure if the panel is needed, but this is how I was able to be sure I was getting the value back. Is there a way to go straight from submit to PDF and print?
Use something like http://code.google.com/p/wkhtmltopdf/
This roughly outlines how to do it: https://stackoverflow.com/a/18767473/181771
I made an asp.net website demo taking the contents of a panel or div and generating a pdf from the html. This is using NReco.PdfGenerator (another wkhtmltopdf wrapper):
https://github.com/jay8anks/Asp.net-HtmlToPdf_NReco.PdfGenerator
Yeah, it's a webform, but anyone sharp enough to do mvc should be able to adapt it fairly easily.
Basically, it is using javascript to get the html between a panel (div) tag and store it in a hiddenfield. Pretty straight forward, except if you want to have css or images, you can't use a relative url for them. I actually just embedded the css inline as a string, but there are other ways of doing it.
Then in the codebehind, this gets the html and generates a pdf from it:
protected void SaveHtmlToPdf()
{
string htmlOutput = Server.UrlDecode(HiddenField1.Value);
htmlOutput = string.Join(" ", System.Text.RegularExpressions.Regex.Split(htmlOutput, #"(?:\r\n|\n|\r|\t)"));
htmlOutput = htmlOutput.Replace("\"", "'");
string headerStyle = HeaderStyle();
string finalHtml = headerStyle + htmlOutput;
var strWr = new StringWriter();
var htmlWr = new HtmlTextWriter(strWr);
// base.Render(htmlWr);
var htmlToPdf = new HtmlToPdfConverter();
string filename = (orderId + ".pdf");
string filepath = "~/sales_pdfs";
string combinedFilePath = Path.Combine(Server.MapPath(filepath), filename).ToString();
for (int i = 1; i <= NumberOfRetries; ++i)
{
try
{
htmlToPdf.GeneratePdf(finalHtml, null, combinedFilePath);
break; // When done we can break loop
}
catch (IOException e)
{
// You may check error code to filter some exceptions, not every error
// can be recovered.
if (i <= NumberOfRetries)
{
Thread.Sleep(DelayOnRetry);
}
ltMsg.Text = "There was a problem creating the PDF";
}
}
}
This puts a pdf in a directory so it can be downloaded, but there are other ways that could be handled, as well. We actually wanted a copy of the PDF that someone was generating, so this was the direction we went in.

How to set focus at the end of textbox while typing?

I have a textbox with a live search function. It is working all good except one problem. If I type any characters on it, it just loses its focus. If I set textbox.Focus(), the cursor goes at the beginning of the textbox.
I have tried most of solutions on the internet. Please check my codes below.
asp:TextBox ID="searchCompany" runat="server" Text="" CssClass="searchCompany" AutoPostBack="true" Width="190px" OnTextChanged="searchCompany_TextChanged"></asp:TextBox>
In page_Load
protected void Page_Load(object sender, EventArgs e)
{
//ScriptManager1.RegisterAsyncPostBackControl(Menu1);
menuDisplay();
searchCompany.Attributes.Add("onkeyup", "setTimeout('__doPostBack(\\'" + searchCompany.UniqueID + "\\',\\'\\')', 0);");
//searchCompany.Attributes.Add("onfocus", "javascript:setSelectionRange('" + "','')");
//searchCompany.Focus();
}
and I have tried javascript as below
<script type="text/javascript">
function setSelectionRange() {
var inputField = document.getElementById('searchCompany');
if (inputField != null && inputField.value.length > 0) {
if (inputField.createTextRange) {
var FieldRange = inputField.createTextRange();
FieldRange.moveStart('character',inputField.value.length);
FieldRange.collapse();
FieldRange.select();
}
}
}
</script>
I have tried to put codes on a method "searchCompany_TextChanged" which is calling if user type any characters on a textbox everytime however it is not working as well.
I saw other solutions with using Textbox.Select() but System.Windows.Control is not working in asp.net i guess.
Any idea??
There's a very simple trick that's worked for me. Basically, set the text value of the of input to itself to its own text value, and that will move the cursor to the end of the text. Then just focus it. This code uses jQuery to demonstrate that, but you should be able to do that in straight JS as well.
HTML
<input type="text" id="focusText"></input>
<button id="focusButton">Set Focus</button>
JavaScript
$("#focusButton").click(function() {
var text = $("#focusText").val();
$("#focusText").val(text).focus();
})
Here's a non jQuery example of the JavaScript, HTML should be the same:
document.getElementById("focusButton").onclick = function() {
var inputElement = document.getElementById("focusText");
var text = inputElement.value;
inputElement.value = text;
inputElement.focus();
}
Here's a fiddle demonstrating the non-jQuery version of the code: http://jsfiddle.net/C3gCa/

Change color of text box with CustomValidator

I am creating some text boxes at runtime and I would like to change the color of the text box if the text box has been left blank
and the user submits the form.
I am using the code behind approach, this is the code I wrote in the .aspx.cs file
textBoxObj is the text box object that I create at runtime and it is the object on which I want the empty validation.
CustomValidator customValidatorObj = new CustomValidator();
customValidatorObj.ControlToValidate = textBoxObj.ID;
customValidatorObj.ClientValidationFunction = "changeColorofTextBox";
and I wrote a small Javascript snippet within the .aspx file which goes as follows (I haven't yet written the logic to change the color,
just making it not valid for now)
<script type="text/javascript">
function changeColorofTextBox(oSrc, args) {
if (args.Value.length > 0) {
args.IsValid = true;
}
else {
args.IsValid = false;
}
}
</script>
In the submit button click function of the form, I have this check if(Page.IsValid), then submit the form. However, even when the text box is empty,
the form gets submitted. It seems like the function is not even being hit. Do you have any pointers on what I am doing wrong?
I am fine with either client side or server side validation, whichever works.
EDIT
I got the error, I just had to do this
customValidatorObj.ValidateEmptyText = true;
and it started working.. Thank you, I didn't realize that the customValidator class does not try validating if the control is blank.
But I am stuck again :(
In the form, I have many text boxes. Suppose, the user entered text for 3 of the text boxes and left 2 of them blank, how do I find the text box ids so that I can change the color of only the blank ones. or, how can I write code in the javascript to find out the control ID at runtime?
I know we have to do this
document.getElementById(CONTROLIDGOESHERE).style.backgroundColor = "red";
but how I get the CONTROLIDGOESHERE value to pass to the getElementById function?
Any pointers, thanks.
Try setting customValidatorObj.EnableClientScipt = True
Assuming you are running .NET Framework version 4.0 then you could declare your textboxes using ClientIDMode="Static". That way they'll have the same ID client-side and server-side e.g.
<asp:TextBox runat="server" ID="txtName" ClientIDMode="Static" />
Then you could trigger client-side validation on a button click by declaring a button like this:
<input type="submit" id="btnSubmit" onclick="ClientSideValidation(); return false;" value="Save"/>
The JavaScript function could look something like this:
<script type="text/javascript">
function ClientSideValidation() {
var txtName = document.getElementById("txtName");
if (txtName.value.length == 0) {
txtName.style.background = "#DE0000";
}
// Check other text boxes...
}
</script>
Thank you guys, I figured it out. This code does the job for me
.aspx.cs
CustomValidator customValidator = new CustomValidator();
customValidator.ControlToValidate = textBox.ID;
customValidator.ClientValidationFunction = "changeColorofTextBox";
customValidator.ValidateEmptyText = true;
customValidator.EnableClientScript = true;
e.Item.Controls.Add(customValidator);
.aspx
<script type="text/javascript">
function changeColorofTextBox(oSrc, args) {
if (args.Value.length > 0) {
args.IsValid = true;
}
else {
var ctrlid = oSrc.id;
var validatorid = document.getElementById(ctrlid);
ctrlid = validatorid.controltovalidate;
document.getElementById(ctrlid).style.backgroundColor = "Tomato";
args.IsValid = false;
}
}
</script>

Categories

Resources