Winforms - Underline part of text to be displayed in textbox - c#

I have a line of text to display and what I want to do is underline only the heading portion of the text in the display. How do I accomplish this please?
Message: This is a message for Name of Client.
Where "Message:" is underlined.

Use RichTextBox instead !
this.myRichTextBox.SelectionStart = 0;
this.myRichTextBox.SelectionLength = this.contactsTextBox.Text.Length-1;
myRichTextBox.SelectionFont = new Font(myRichTextBox.SelectionFont, FontStyle.Underline);
this.myRichTextBox.SelectionLength = 0;

You can do that underline using the RichTextBox control
int start = rtbTextBox.Text.IndexOf("Message:", StringComparison.CurrentCultureIgnoreCase);
if(start > 0)
{
rtbTextBox.SelectionStart = start;
rtbTextBox.SelectionLength = "Message:".Length-1;
rtbTextBox.SelectionFont = new Font(rtbTextBox.SelectionFont, FontStyle.Underline);
rtbTextBox.SelectionLength = 0;
}
This example use directly the text you provided in your question. It will be better if you encapsulate this code in a private method and pass in the heading text.
For example:
private void UnderlineHeading(string heading)
{
int start = rtbTextBox.Text.IndexOf(heading, StringComparison.CurrentCultureIgnoreCase);
if(start > 0)
{
rtbTextBox.SelectionStart = start;
rtbTextBox.SelectionLength = heading.Length-1;
rtbTextBox.SelectionFont = new Font(rtbTextBox.SelectionFont, FontStyle.Underline);
rtbTextBox.SelectionLength = 0;
}
}
and call from your form whith: UnderlineHeading("Message:");

If you want to show the text using a rich text box, you could do something like this:
richTextBox1.SelectionFont = new Font("Times New Roman", 10, FontStyle.Underline);
richTextBox1.SelectedText = "Message:";
richTextBox1.SelectionFont = new Font("Times New Roman", 10, FontStyle.Regular);
richTextBox1.SelectedText = " This is a message for Name of Client.";
Or, if the message is dynamic and the header and text are always separated by a colon, you could do something like this:
string message = "Message: This is a message for Name of Client";
string[] parts = message.Split(':');
richTextBox1.SelectionFont = new Font("Times New Roman", 10, FontStyle.Underline);
richTextBox1.SelectedText = parts[0] + ":";
richTextBox1.SelectionFont = new Font("Times New Roman", 10, FontStyle.Regular);
richTextBox1.SelectedText = parts[1];
Or, if you want to show the text dynamically in labels, you could do something like this:
string message = "Message: This is a message for Name of Client";
string[] parts = message.Split(':');
Label heading = new Label();
heading.Text = parts[0] + ":";
heading.Font= new Font("Times New Roman", 10, FontStyle.Underline);
heading.AutoSize = true;
flowLayoutPanel1.Controls.Add(heading);
Label message = new Label();
message.Text = parts[1];
message.Font = new Font("Times New Roman", 10, FontStyle.Regular);
message.AutoSize = true;
flowLayoutPanel1.Controls.Add(message);

Just a thought, You can use masked text box or create a custom control with richtextbox having underline and use it in client application. I heard there is a chance of creating textbox with underline using GDI+ api but not sure.
Thanks
Mahesh kotekar

Related

How to set text alignment in dynamically created FixedDocument

I am creating a report through FixedDocument and I am doing it in the code behind to dynamically add data to the report.
I started using FixedDocument today and got stuck in aligning texts. It does not seem to center align. Here's my code:
using System.Windows.Documents;
....
public void GenerateReport()
{
FixedDocument document = new FixedDocument();
PageContent content = new PageContent();
FixedPage page = new FixedPage();
page.Width = document.DocumentPaginator.PageSize.Width;
page.Height = document.DocumentPaginator.PageSize.Height;
page.Background = System.Windows.Media.Brushes.AliceBlue;
//header first line
System.Windows.Controls.Canvas canvas = new System.Windows.Controls.Canvas();
canvas.Width = document.DocumentPaginator.PageSize.Width;
FixedPage.SetTop(canvas, 15);
FixedPage.SetLeft(canvas, 15);
System.Windows.Controls.TextBlock block = new System.Windows.Controls.TextBlock();
block.FontSize = 11;
block.FontWeight = FontWeights.Bold;
block.FontFamily = new System.Windows.Media.FontFamily("Tahoma");
block.Text = "This is the first line";
block.HorizontalAlignment = HorizontalAlignment.Center;
canvas.Children.Add(block);
page.Children.Add(canvas);
//header second line
System.Windows.Controls.TextBlock block2 = new System.Windows.Controls.TextBlock(); block.FontSize = 11;
block2.FontWeight = FontWeights.Bold;
block2.FontFamily = new System.Windows.Media.FontFamily("Tahoma");
block2.Text = "Daily Report";
var canvas2 = new System.Windows.Controls.Canvas();
canvas2.Children.Add(block2);
FixedPage.SetTop(canvas2, 30);
FixedPage.SetTop(canvas2, 30);
FixedPage.SetLeft(canvas2, 15);
FixedPage.SetRight(canvas2, 15);
canvas2.Width = document.DocumentPaginator.PageSize.Width;
page.Children.Add(canvas2);
((IAddChild)content).AddChild(page);
document.Pages.Add(content);
}
How will I do the alignment right?
https://learn.microsoft.com/en-us/dotnet/api/system.windows.documents.flowdocument?view=net-5.0#properties
I'm not sure if you can do this with FixedDocument. This is available in Flowdocument though with the TextAlignmentProperty.

Auto Complete works for only the first character typed

I am using Telerik Raddropdownlist and have set the auto complete mode to suggest. When I type the first character in the text box, say '1', the dropdown suggests all projects starting with 1 which is fine( Lets say the first 2 projects listed after the match1 are 1234 and 1456). However, when I type lets say another '1', the textbox gets appended with "111234" which is basically both the 1s I typed along with the first element in the dropdown. Though the autocomplete mode is suggest and not suggestappend, I have no idea why the first match gets appended.
this.radDropDownList1.AutoCompleteMode = System.Windows.Forms.AutoCompleteMode.Suggest;
this.radDropDownList1.AutoSizeItems = true;
this.radDropDownList1.DefaultItemsCountInDropDown = 20;
this.radDropDownList1.DropDownHeight = 160;
this.radDropDownList1.DropDownMinSize = new System.Drawing.Size(400, 200);
this.radDropDownList1.Font = new System.Drawing.Font("Microsoft Sans Serif", 10F);
this.radDropDownList1.Location = new System.Drawing.Point(803, 23);
this.radDropDownList1.MaxDropDownItems = 10;
this.radDropDownList1.Name = "radDropDownList1";
this.radDropDownList1.RootElement.AutoSize = false;
this.radDropDownList1.Size = new System.Drawing.Size(280, 36);
this.radDropDownList1.TabIndex = 2;
this.radDropDownList1.Text = "Select Project";
this.radDropDownList1.DropDownListElement.AutoCompleteSuggest.DropDownList.Popup.Font = new System.Drawing.Font("Microsoft Sans Serif", 16);
this.radDropDownList1.SelectedIndexChanged += new Telerik.WinControls.UI.Data.PositionChangedEventHandler(this.raddropdownlist_SelectedIndexChanged);
radDropDownList1.DataSource = ditems;
radDropDownList1.DisplayMember = "ProjectName";
radDropDownList1.ValueMember = "ProjectName";
radDropDownList1.AutoCompleteDataSource = ditems;
radDropDownList1.AutoCompleteMode = AutoCompleteMode.Suggest;
Size popupSize = new Size(400, 300);
radDropDownList1.DropDownListElement.AutoCompleteSuggest.DropDownList.DropDownMinSize = popupSize;
radDropDownList1.DropDownListElement.DropDownMinSize = popupSize;
radDropDownList1.ListElement.Font = new Font("Microsoft Sans Serif",16);
radDropDownList1.DropDownListElement.AutoCompleteSuggest.DropDownList.Popup.Font = new System.Drawing.Font("Microsoft Sans Serif", 16);
}
catch (Exception ex)
{
Utils.LogManager.write("Exception occur While populating Projects. error detail: " + ex.Message + "\r\nStacktrace: " + ex.StackTrace, "error");
ExceptionDialog.ShowExceptionDialog(ex);
}
radDropDownList1.SelectedIndex = -1;
radDropDownList1.Text = "Select Project";
private void raddropdownlist_SelectedIndexChanged(object sender, Telerik.WinControls.UI.Data.PositionChangedEventArgs e)
{
if (radDropDownList1.SelectedIndex >=0)
{
cbTaskList.Select();
PopulateTasks();
if (this.GetMainForm().IsResetApp)
{
return;
}
}
}
I know theres a lot of redundancy in my code but I had a tough time resizing my AutoSuggest popup and I'm also new to this.
radDropDownList1.DropDownListElement.AutoCompleteSuggest.DropDownList.Popup.Font = new System.Drawing.Font("Microsoft Sans Serif", 16);
was causing it to behave weird. It worked fine once I commented it out.

iTextsharp underline between strings

I am using iTextsharp tp create PDF. I have following lines of code to show text on PDF.
var contentByte = pdfWriter.DirectContent;
contentByte.BeginText();
contentByte.SetFontAndSize(baseFont, 10);
var multiLine = " Request for grant of leave for ____2______days";
contentByte.ShowTextAligned(PdfContentByte.ALIGN_LEFT, multiLine, 100, 540, 0);
contentByte.EndText();
I need to replace "____" with underline. On underline "2" should display.
Please help me to solve this.
I solved this by your answer. thank u.. # Chris Haas
var baseFont = BaseFont.CreateFont(fontFile, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
var mainFont = new iTextSharp.text.Font(baseFont, 10);
//Our Phrase will hold all of our chunks
var p = new Phrase();
//Add the start text
p.Add(new Chunk("Request for grant of leave for ", mainFont));
var space1 = new Chunk(" ", FontFactory.GetFont(FontFactory.HELVETICA, 12.0f, iTextSharp.text.Font.BOLD | iTextSharp.text.Font.UNDERLINE));
p.Add(space1);
//Add our underlined text
var c = new Chunk("2", mainFont);
c.SetUnderline(0.1f, -1f);
p.Add(c);
var space1 = new Chunk(" ", FontFactory.GetFont(FontFactory.HELVETICA, 12.0f, iTextSharp.text.Font.BOLD | iTextSharp.text.Font.UNDERLINE));
p.Add(space1);
//Add our end text
p.Add(new Chunk(" days", mainFont));
//Draw our formatted text
ColumnText.ShowTextAligned(pdfWriter.DirectContent, PdfContentByte.ALIGN_LEFT, p, 100, 540, 0);
Instead of using a PdfContentByte directly which only allows you to draw strings you can use a ColumnText which allows you access to iText's abstractions, specifically a Chunk which has a SetUnderline() method on it.
//Create our base font and actual font
var baseFont = BaseFont.CreateFont(fontFile, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
var mainFont = new iTextSharp.text.Font(baseFont, 10);
//Our Phrase will hold all of our chunks
var p = new Phrase();
//Add the start text
p.Add(new Chunk("Request for grant of leave for ", mainFont));
//Add our underlined text
var c = new Chunk("2", mainFont);
c.SetUnderline(0.1f, -1f);
p.Add(c);
//Add our end text
p.Add(new Chunk(" days", mainFont));
//Draw our formatted text
ColumnText.ShowTextAligned(pdfWriter.DirectContent, PdfContentByte.ALIGN_LEFT, p, 100, 540, 0);

TextBlock with multiple lines by code on Windows Phone 8

I have a string containing some text (note the \n),
string mText = "Hello\nWorld";
When I apply this to a TextBlock (generated by code) like this:
TextBlock tb = new TextBlock();
tb.Foreground = (Brush)App.Current.Resources["PhoneForegroundBrush"];
tb.FontSize = (double)App.Current.Resources["PhoneFontSizeMedium"];
tb.Margin = new Thickness(24, 32, 24, 12);
tb.TextWrapping = TextWrapping.Wrap;
tb.Text = mText;
I don't see the second line. Any ideas?
[UPDATE - Added the usage of this code]
I use this in showing a PopUp on the Screen:
// Create PopUp Content:
TextBlock tb = new TextBlock();
tb.Foreground = (Brush)App.Current.Resources["PhoneForegroundBrush"];
tb.FontSize = (double)App.Current.Resources["PhoneFontSizeMedium"];
tb.Margin = new Thickness(24, 32, 24, 12);
tb.TextWrapping = TextWrapping.Wrap;
tb.Text = pMessage;
Grid grid = new Grid();
grid.Background = (Brush)App.Current.Resources["PhoneAccentBrush"];
grid.Children.Add(tb);
grid.Width = page.ActualWidth;
// Create PopUp itself:
Popup popup = new Popup();
popup.Child = grid;
// Show PopUp:
SystemTray.BackgroundColor = (Color)App.Current.Resources["PhoneAccentColor"];
popup.IsOpen = true;
You could also add the following:
tb.Text = mText + Environment.NewLine;
or
tb.Text = mText + "
" + "
"
that seems to insert the <LineBreak/> into.

How to display ✔ in PDF using iTextSharp?

I am trying to display the "✔" character in a PDF using iTextSharp. However the character won't show up on the created PDF. Please help me on this.
Phrase phrase = new Phrase("A check mark: ");
Font zapfdingbats = new Font(Font.FontFamily.ZAPFDINGBATS);
phrase.Add(new Chunk("\u0033", zapfdingbats));
phrase.Add(" and more text");
document.Add(phrase);
Font Wingdings prints this character instead of "o".
You need to connect this font to your application, then apply this font to letter and embedd the font into pdf for compatibility.
This is my function (not cleaned) that I have used in one of my projects a while back.
please clean it up, but it has some essential features that you need. (I had my custom fonts (font1.ttf and font2.ttf) copied in the project directory)
I am hoping it will help you.
public void StartConvert(String originalFile, String newFile)
{
Document myDocument = new Document(PageSize.LETTER);
PdfWriter.GetInstance(myDocument, new FileStream(newFile, FileMode.Create));
myDocument.Open();
int totalfonts = FontFactory.RegisterDirectory("C:\\WINDOWS\\Fonts");
iTextSharp.text.Font content = FontFactory.GetFont("Pea Heather's Handwriting", 13);//13
iTextSharp.text.Font header = FontFactory.GetFont("assign", 16); //16
BaseFont customfont = BaseFont.CreateFont(#"font1.ttf", BaseFont.CP1252, BaseFont.EMBEDDED);
Font font = new Font(customfont, 13);
string s = " ";
myDocument.Add(new Paragraph(s, font));
BaseFont customfont2 = BaseFont.CreateFont(#"font2.ttf", BaseFont.CP1252, BaseFont.EMBEDDED);
Font font2 = new Font(customfont2, 16);
string s2 = " ";
myDocument.Add(new Paragraph(s2, font2));
try
{
try
{
using (StreamReader sr = new StreamReader(originalFile))
{
// Read and display lines from the file until the end of
// the file is reached.
String line;
while ((line = sr.ReadLine()) != null)
{
String newTempLine = "";
String[] textArray;
textArray = line.Split(' ');
newTempLine = returnSpaces(RandomNumber(0, 6)) + newTempLine;
int counterMax = RandomNumber(8, 12);
int counter = 0;
foreach (String S in textArray)
{
if (counter == counterMax)
{
Paragraph P = new Paragraph(newTempLine + Environment.NewLine, font);
P.Alignment = Element.ALIGN_LEFT;
myDocument.Add(P);
newTempLine = "";
newTempLine = returnSpaces(RandomNumber(0, 6)) + newTempLine;
}
newTempLine = newTempLine + returnSpaces(RandomNumber(1, 5)) + S;
counter++;
}
Paragraph T = new Paragraph(newTempLine, font2);
T.Alignment = Element.ALIGN_LEFT;
myDocument.Add(T);
}
}
}
catch (Exception e)
{
Console.WriteLine("The file could not be read:");
Console.WriteLine(e.Message);
}
}
catch (DocumentException de)
{
Console.Error.WriteLine(de.Message);
}
catch (IOException ioe)
{
Console.Error.WriteLine(ioe.Message);
}
try
{
myDocument.Close();
}
catch { }
}
Define font at master
protected static Font ZAPFDINGBATS(float size, bool bold = false, bool italic = false, bool underline = false, Color color = null)
=> new(StandardFonts.ZAPFDINGBATS, size, bold, italic, underline, color);
declare font
private readonly Font ZapFont = ZAPFDINGBATS(10, bold: false, color: ColorConstants.BLACK);
private readonly Action<Cell> _cellRight = cell => cell.RemoveBorder().SetTextAlignment(TextAlignment.RIGHT);
Use
document.AddTable(
columns: new float[1]
{
100
},
table => table.SetWidth(document.GetPageEffectiveArea(PageSize).GetWidth())
.SetMargins(0, 0, 0, 0)
.AddCell(model.IsTrue ? "4" : "o", ZapFont, _cellRight );
This worked for me:
pdfStamper.FormFlattening = true;

Categories

Resources