Dynamic size two dimensional array - arrays

I'm currently working on a webshop. For that i need to make a two dimensional array to store the items moved to the cart.
Cart:
Cart = Session("Cart")
Items = Session("Items")
And when an item is moved to the cart:
Items = Items + 1
Cart(1,Items) = Items
Cart(2,Items) = rs("id")
Cart(3,Items) = Request("attr")
Cart(4,Items) = rs("name")
Cart(5,Items) = rs("price")
Cart(6,Items) = 1
And finally:
Session("Cart") = Cart
Session("Items") = Items
But i'm having issues with the asp lack of proper support of dynamic sized two-dimensional arrays. Or am i just taking it the wrong way? Can you help me?

You might want to create some objects instead of using arrays. Or even a structure, if it's got no methods.
Here's an expamle of a struct
/// <summary>
/// Custom struct type, representing a rectangular shape
/// </summary>
struct Rectangle
{
/// <summary>
/// Backing Store for Width
/// </summary>
private int m_width;
/// <summary>
/// Width of rectangle
/// </summary>
public int Width
{
get
{
return m_width;
}
set
{
m_width = value;
}
}
/// <summary>
/// Backing store for Height
/// </summary>
private int m_height;
/// <summary>
/// Height of rectangle
/// </summary>
public int Height
{
get
{
return m_height;
}
set
{
m_height = value;
}
}
}
so now you can:
Cart[0] = new Rectangle{Width = 1,Height = 3};
or
Rectangle myRec = new Rectangle();
myRec.Height = 3;
myRec.Width = 1;
Cart[0] = myRec;
Swap the Rectangle example with Item, and you should be on your way.
That way, a single instance of each Cart multiple Items that each have their own set of properties.

Would it not be simpler to store a ShoppingSessionID for the user that's related to a table that stores a list of items in the cart? that way all you have to store is Session("ShoppingSessionID").

It seems to me that your problem could be solved with a dynamically sized list of item objects. In that case you would want to create an Item class and then add to the Cart list a new Item object for each new item.

Related

How to suppress launching beyond compare 3 while doing a comparison from windows forms application

I am using Beyond Compare 3 in my win forms application to do a comparison in two output folders (ProdOutput and SITOutput). I am using the below lines of code for doing the comparison
public static void LaunchViewer(string filepath1, string filepath2)
{
string arguments = String.Format("\"{0}\" \"{1}\"", filepath1, filepath2);
ProcessStartInfo psi = new ProcessStartInfo(ApplicationPath, arguments);
using (Process p = Process.Start(psi))
{
ComparsionResult = CompareFiles(filepath1, filepath2, BeyondCompareRules.EverythingElse);
}
}
public static ComparisonResult CompareFiles(string filepath1, string filepath2, string ruleName)
{
ComparisonResult result = ComparisonResult.None;
string arguments = String.Format("/quickcompare /rules=\"{0}\" \"{1}\" \"{2}\"", ruleName, filepath1, filepath2);
ProcessStartInfo psi = new ProcessStartInfo(ApplicationPath, arguments);
psi.UseShellExecute = false;
psi.RedirectStandardInput = true;
psi.RedirectStandardOutput = true;
using (Process p = Process.Start(psi))
{
p.StandardInput.WriteLine("EXIT [ErrorLevel]");
p.WaitForExit();
int exitCode = p.ExitCode;
switch (exitCode)
{
case 0:
result = ComparisonResult.Match;
break;
case 1:
result = ComparisonResult.Similar;
break;
case 2:
result = ComparisonResult.DoNotMatch;
break;
case 3:
result = ComparisonResult.ComparisonError;
break;
default :
result = ComparisonResult.DoNotMatch;
break;
}
}
return result;
}
Beyond compare rules are below
public sealed class BeyondCompareRules
{
private BeyondCompareRules()
{
}
/// <summary>
/// A comparison rule set for C/C++/C# source files
/// </summary>
public const string CLanguageSource = "C/C++/C# Source";
public const string Cobol = "COBOL";
public const string CommaSeparatedValues = "Comma Separated Values";
public const string DelphiSource = "Delphi Source";
public const string DelphiForms = "Delphi Forms";
public const string GeneralText = "General Text";
public const string Html = "HTML";
public const string Java = "JAVA";
public const string Python = "Python";
public const string RegistryDump = "Registry Dump";
public const string Utf8Text = "UTF8 Text";
public const string VisualBasic = "Visual Basic";
public const string Xml = "XML";
/// <summary>
/// The default set of comparison rules
/// </summary>
public const string EverythingElse = "Everything Else";
}
and comparisonresult is an enum as below
public enum ComparisonResult
{
/// <summary>
/// Indicates a null or uninitialized value
/// </summary>
None = 0,
/// <summary>
/// The Quick Compare returned a Positive Match
/// </summary>
Match = 1,
/// <summary>
/// The Quick Compare detected small differences
/// </summary>
Similar = 2,
/// <summary>
/// The Quick Compare detected significant differences
/// </summary>
DoNotMatch = 3,
/// <summary>
/// The Quick Compare utility returned an error/unknown result
/// </summary>
ComparisonError = 4
}
What I need is to suppress launching the beyond compare screen when doing the comparison but the comparison should happen and it should return result. Now with my above code I am able to do the comparison and also able to view the differences which I don't want to do.
I guess there is some thing which I can do with passing arguments but not sure what is it and how and where should I put it.
Any help highly appreciated.
After several trials with different ways to achieve the functionality, finally a small piece of code did resolved the issue.
There is a command line switches available for beyond compare application which needs to be passed when we want to suppress the interactions. It is called "/silent".
I have passed along with these lines in CompareFiles method
public static ComparisonResult CompareFiles(string filepath1, string filepath2, string ruleName)
ComparisonResult result = ComparisonResult.None;
string arguments = String.Format("/quickcompare /rules=\"{0}\" \"{1}\" \"{2}\" /silent", ruleName, filepath1, filepath2);
All the above posted code in my question is working fine and can be used by any one who wants to suppress the interactions.

XNA Arrays and drawing textures?

I am completely new to coding and have only been practicing for a few weeks and i have been assigned a task in which seems simple has hit a stumbling block
i have 4 sprites on screen drawn but i have to every time the game starts the sprites have to be random chosen between 1 sprite or the other as well out of the 2 sprites there must be at least one of each sprite on screen.
my tutor suggested that i use an array to store the textures and then code it so it randomly picks which one to draw each time
namespace GamesProgrammingAssement1
{
/// <summary>
/// This is the main type for your game
/// </summary>
public class Game1 : Microsoft.Xna.Framework.Game
{
GraphicsDeviceManager graphics;
SpriteBatch spriteBatch;
KeyboardState keys;
KeyboardState oldKeys;
GamePadState Pad1;
GamePadState oldPad1;
Texture2D gnome;
Texture2D troll;
Rectangle sprRect1;
Rectangle sprRect2;
Rectangle sprRect3;
Rectangle sprRect4;
SpriteFont Run;
SpriteFont Score;
int scoreNum = 0;
int runNum = 0;
Vector2 scorePos;
Vector2 runPos;
Texture2D[] sprite = new Texture2D[2];
public Game1()
{
graphics = new GraphicsDeviceManager(this);
Content.RootDirectory = "Content";
}
/// <summary>
/// Allows the game to perform any initialization it needs to before starting to run.
/// This is where it can query for any required services and load any non-graphic
/// related content. Calling base.Initialize will enumerate through any components
/// and initialize them as well.
/// </summary>
protected override void Initialize()
{
sprRect1 = new Rectangle(375, 100, 64, 64);
sprRect2 = new Rectangle(375, 300, 64, 64);
sprRect3 = new Rectangle(225, 200, 64, 64);
sprRect4 = new Rectangle(525, 200, 64, 64);
scorePos = new Vector2(5, 400);
runPos = new Vector2(5, 425);
sprite[0] = gnome;
sprite[1] = troll;
base.Initialize();
}
/// <summary>
/// LoadContent will be called once per game and is the place to load
/// all of your content.
/// </summary>
protected override void LoadContent()
{
// Create a new SpriteBatch, which can be used to draw textures.
spriteBatch = new SpriteBatch(GraphicsDevice);
gnome = Content.Load<Texture2D>("Gnome");
troll = Content.Load<Texture2D>("Troll");
Score = Content.Load<SpriteFont>("Score");
Run = Content.Load<SpriteFont>("Run");
}
/// <summary>
/// UnloadContent will be called once per game and is the place to unload
/// all content.
/// </summary>
protected override void UnloadContent()
{
// TODO: Unload any non ContentManager content here
}
/// <summary>
/// Allows the game to run logic such as updating the world,
/// checking for collisions, gathering input, and playing audio.
/// </summary>
/// <param name="gameTime">Provides a snapshot of timing values.</param>
protected override void Update(GameTime gameTime)
{
KeyboardState keys = Keyboard.GetState();
KeyboardState oldkeys = keys;
if (keys.IsKeyDown(Keys.Escape)) this.Exit();
// TODO: Add your update logic here
base.Update(gameTime);
}
/// <summary>
/// This is called when the game should draw itself.
/// </summary>
/// <param name="gameTime">Provides a snapshot of timing values.</param>
protected override void Draw(GameTime gameTime)
{
GraphicsDevice.Clear(Color.CornflowerBlue);
spriteBatch.Begin();
spriteBatch.Draw(gnome,sprRect1,Color.White);
spriteBatch.Draw(troll, sprRect2,Color.White);
spriteBatch.Draw(troll, sprRect3, Color.White);
spriteBatch.Draw(troll, sprRect4, Color.White);
spriteBatch.DrawString(Score, "SCORE : "+ scoreNum, scorePos, Color.Black);
spriteBatch.DrawString(Run, "RUN OF TROLL : " + runNum, runPos, Color.Black);
spriteBatch.End();
base.Draw(gameTime);
}
}
}
any help would be great because i dont know if im storing the arrays properly or if im doing random right
I see you are storing your Textures in an Array. I do not see any code for Random in your sample.
That being said, consider the following function:
Random rand = new Random();
private Texture2D GetRandomTexture()
{
return sprite[rand.Next(0, 2)];
}
Calling this function, will return a random texture contained in your "sprite" array. Plugging this function call in your draw could resemble something like this:
spriteBatch.Draw(GetRandomTexture(), sprRect1, Color.White);
Since you declared that you are a beginner, I tried not to go too much into details. You should, however, considering looking into creating a new class "Sprite" that would contain the Texture2D, Position, Rectangle values of each of your sprites. Then instead of storing an array of Textures, you would be able of storing an array (or list) of Sprite objects.
You want to choose four sprites, therefore you should use an array (or similar structure) which can contain four elements:
Texture2D[] sprites = new Texture2D[4];
When initializing the Array there are three possible situations regarding how many of each sprite will exist:
1-3 (one troll, three gnomes)
2-2 (two of each)
3-1 (three trolls, one gnome)
So firstly, you have to pick one of these distributions:
var rnd = new Random();
var trolls = rnd.Next(1, 3);
var gnomes = 4 - trolls;
Then, you can fill the array:
for(int i = 0; i < 4; ++i)
{
if(gnomes == 0)
{
//choose the troll
sprites[i] = troll;
--trolls;
}
else if(trolls == 0)
{
//choose the gnome
sprites[i] = gnome;
--gnomes;
}
else
{
//choose randomly
if(rnd.Next(2) < 1)
{
sprites[i] = troll;
--trolls;
}
else
{
sprites[i] = gnome;
--gnomes;
}
}
}
You draw them like
spriteBatch.Draw(sprites[0], sprRect1,Color.White);
spriteBatch.Draw(sprites[1], , sprRect2,Color.White);
spriteBatch.Draw(sprites[2], , sprRect3, Color.White);
spriteBatch.Draw(sprites[3], , sprRect4, Color.White);

Themes and Languages Resource Dictionary

I was using the standard approach to themes in my WPF application and using a dynamicresource to change it during runtime.
This worked.
Now I have added language support (english, spanish) but when this is set, the dynamic resource no longer works for the theme. If I set the control to a static resource the theme works but then I lose the affect of changing it during runtime.
Heres the code that was added for language support but I'm confused as to why it stopped working the way I want it to.
App.xaml.cs calls this:
SetLanguage(LocalePath(CultureInfo.CurrentCulture.Name));
/// <summary>
/// Get the locale path for the resource dictionary.
/// </summary>
/// <param name="language"></param>
/// <returns></returns>
private string LocalePath(string language)
{
string file = language + ".xaml";
return Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), #"Utilities\Resources\Locales\", file);
}
/// <summary>
/// Set the language using the defined resource file.
/// </summary>
/// <param name="file"></param>
private void SetLanguage(string file)
{
if (File.Exists(file))
{
var languageDictionary = new ResourceDictionary();
languageDictionary.Source = new Uri(file);
int dictionaryID = -1;
for (int i = 0; i < Resources.MergedDictionaries.Count; i++)
{
var mergedDictionary = Resources.MergedDictionaries[i];
if (mergedDictionary.Contains("ResourceDictionaryName"))
{
if (mergedDictionary["ResourceDictionaryName"].ToString().StartsWith("Locale-"))
{
dictionaryID = i;
break;
}
}
}
if (dictionaryID == -1)
{
Resources.MergedDictionaries.Add(languageDictionary);
}
else
{
Resources.MergedDictionaries[dictionaryID] = languageDictionary;
}
}
}
I had 5 other keys in the language resource dictionaries with the same key as the theme being used. Changed the key name and it works again.

Programmatically create ItemsPanelTemplate for Silverlight ComboBox?

I am trying to create a Blend behavior related to ComboBoxes. In order to get the effect I want, the ItemsPanel of the ComboBox has to have a certain element added to it. I don't want to do this in every ComboBox that uses the behavior, so I want the Behavior to be able to inject the ItemsPanelTemplate programmatically. However, I can't seem to find a way to do this. ItemsPanelTemplate does not seem to have a property/method that lets me set the visual tree. WPF ItemsPanelTemplate has the VisualTree but Silverlight does not.
Basically, what is the programmatic equivalent of this XAML?
<ComboBox>
<ComboBox.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel/>
</ItemsPanelTemplate>
</ComboBox.ItemsPanel>
</ComboBox>
Edit:
Okay apparently that is not an easy question, so I started a bounty and I'm going to give some more background in case there is another way to go about this. I want to provide keyboard support for the Silverlight ComoboBox. Out of the box it only supports the up and down arrows but I also want it to work so that when the user hits a letter, the ComboBox jumps to the first item of that letter, similar to how ComboBoxes work in a browser or Windows app.
I found this blog post, which got me half way. Adapting that behavior code, the ComboBox will change selection based on letter input. However, it does not work when the ComboBox is opened. The reason for this, according to this blog post is that when the ComboBox is opened, you are now interacting with its ItemsPanel and not the ComboBox itself. So according to that post I actually need to add a StackPanel to the ItemsPanelTemplate and subscribe to the StackPanel's KeyDown event, in order to take action when the ComboBox is opened.
So that is what prompted my question of how to get a StackPanel into the ItemsPanelTemplate of a ComboBox, from a behavior. If that is not possible, are there alternative ways of getting this to work? Yes, I know I could go to each ComboBox in the application and add a StackPanel and the event. But I want to do this through a behavior so that I don't have to modify every ComboBox in the app, and so I can reuse this logic across applications.
AnthonyWJones' answer below using XamlReader gets me part way, in that I can create the StackPanel and get it into the template. However, I need to be able to get at that SP programmatically in order to subscribe to the event.
This should work. I've shown how you can change the orientation below. You can add additional SetValue calls to modify other properties.
cb.ItemsPanel = new ItemsPanelTemplate();
var stackPanelFactory = new FrameworkElementFactory(typeof (StackPanel));
// Modify it like this:
stackPanelFactory.SetValue(StackPanel.OrientationProperty, Orientation.Horizontal);
// Set the root of the template to the stack panel factory:
cb.ItemsPanel.VisualTree = stackPanelFactory;
You can find more detailed information in this article: http://www.codeproject.com/KB/WPF/codeVsXAML.aspx
What you actually want to build programmatically is this:-
<ItemsPanelTemplate>
<StackPanel />
</ItemsPanelTemplate>
Your behaviour will then assign this to the ItemsPanel property of the ComboBox it is attached to. Currently your behaviour is pure code but there is no way to create the above purely in code.
Since this is such a small piece for of Xaml the easiest approach is to use the XamlReader:-
ItemsPanelTemplate itemsPanelTemplate = XamlReader.Load("<ItemsPanelTemplate><StackPanel /></ItemsPanelTemplate>");
I think, best way for you - extend combobox functionality not via behavior but using inheritance.
So, you can create own control MyComboBox:ComboBox. Create style for it - get default ComboBox Style
here
And write instead (look for ScrollViewer by name):
< ScrollViewer x:Name="ScrollViewer" BorderThickness="0" Padding="1" >
< ItemsPresenter />
< /ScrollViewer >
this
< ScrollViewer x:Name="ScrollViewer" BorderThickness="0" Padding="1" >
< StackPanel x:Name="StackPanel" >
< ItemsPresenter />
< /StackPanel >
< /ScrollViewer >
This StackPanel you can get in code:
public class MyComboBox: ComboBox{
public CM()
{
DefaultStyleKey = typeof (MyComboBox);
}
public override void OnApplyTemplate()
{
base.OnApplyTemplate();
StackPanel stackPanel = (StackPanel)GetTemplateChild("StackPanel");
stackPanel.KeyUp += (s, e) => { /*do something*/ };
}
}
Inheritance is more powerful. It's allow work with template elements.
If you decided to inject ItemsPanel, you must understand that:
1)it's impossible from code with keeping reference on injected panel.
2)to get reference to injected panel, this panel must registered itself in some storage, e.g.
< ComboBox>
< ComboBox.ItemsPanel>
< ItemsPanelTemplate>
< StackPanel>
< i:Interaction.EventTriggers>
< i:EventTrigger EventName="Loaded">
< RegisterMyInstanceInAccessibleFromCodePlaceAction/>
< /i:EventTrigger>
< /i:Interaction.EventTriggers>
< /StackPanel>
< /ItemsPanelTemplate>
< /ComboBox.ItemsPanel>
< /ComboBox>
Good luck!
I found your post while trying to set the ItemsPanel from code so that I can implement a VirtualizingStackPanel. When there are hundreds of items in my list, performance sucks. Anyway .. here's how I did it.
1) Custom control
2) Custom Behavior
-- you could also just apply this behavior to the normal ComboBox - either at each instance, or through a style.
-- you might also expose the timeout value so that can be overridden in xaml ..
-- also, it seems this doesn't work when the dropdown itself is open. not sure why exactly .. never looked into it
1..
public class KeyPressSelectionComboBox : ComboBox
{
private BindingExpression _bindingExpression;
public KeyPressSelectionComboBox()
: base()
{
Interaction.GetBehaviors(this).Add(new KeyPressSelectionBehavior());
Height = 22;
this.SelectionChanged += new SelectionChangedEventHandler(KeyPressSelectionComboBox_SelectionChanged);
}
void KeyPressSelectionComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (_bindingExpression == null)
{
_bindingExpression = this.GetBindingExpression(ComboBox.SelectedValueProperty);
}
else
{
if (this.GetBindingExpression(ComboBox.SelectedValueProperty) == null)
{
this.SetBinding(ComboBox.SelectedValueProperty, _bindingExpression.ParentBinding);
}
}
}
}
2...
/// <summary>
/// This behavior can be attached to a ListBox or ComboBox to
/// add keyboard selection
/// </summary>
public class KeyPressSelectionBehavior : Behavior<Selector>
{
private string keyDownHistory = string.Empty;
private double _keyDownTimeout = 2500;
private DateTime _lastKeyDownTime;
private DateTime LastKeyDownTime
{
get
{
if (this._lastKeyDownTime == null)
this._lastKeyDownTime = DateTime.Now;
return this._lastKeyDownTime;
}
set { _lastKeyDownTime = value; }
}
/// <summary>
/// Gets or sets the Path used to select the text
/// </summary>
public string SelectionMemberPath { get; set; }
/// <summary>
/// Gets or sets the Timeout (ms) used to reset the KeyDownHistory item search string
/// </summary>
public double KeyDownTimeout
{
get { return _keyDownTimeout; }
set { _keyDownTimeout = value; }
}
public KeyPressSelectionBehavior() { }
/// <summary>
/// Attaches to the specified object: subscribe on KeyDown event
/// </summary>
protected override void OnAttached()
{
base.OnAttached();
this.AssociatedObject.KeyDown += DoKeyDown;
}
void DoKeyDown(object sender, KeyEventArgs e)
{
// Create a list of strings and indexes
int index = 0;
IEnumerable<Item> list = null;
var path = SelectionMemberPath ??
this.AssociatedObject.DisplayMemberPath;
var evaluator = new BindingEvaluator();
if (path != null)
{
list = this.AssociatedObject.Items.OfType<object>()
.Select(item =>
{
// retrieve the value using the supplied Path
var binding = new Binding();
binding.Path = new PropertyPath(path);
binding.Source = item;
BindingOperations.SetBinding(evaluator,
BindingEvaluator.TargetProperty, binding);
var value = evaluator.Target;
return new Item
{
Index = index++,
Text = Convert.ToString(value)
};
});
}
else
{
list = this.AssociatedObject.Items.OfType<ListBoxItem>()
.Select(item => new Item
{
Index = index++,
Text = Convert.ToString(item.Content)
});
}
// Sort the list starting at next selectedIndex to the end and
// then from the beginning
list = list.OrderBy(item => item.Index <=
this.AssociatedObject.SelectedIndex ?
item.Index + this.AssociatedObject.Items.Count : item.Index);
// calculate how long has passed since the user typed a letter
var elapsedTime = DateTime.Now - this.LastKeyDownTime;
if (elapsedTime.TotalMilliseconds <= this.KeyDownTimeout)
{ /* if it's less than the timeout, add to the search string */
this.keyDownHistory += GetKeyValue(e);
}
else
{ /* otherwise replace it */
this.keyDownHistory = GetKeyValue(e);
}
// Find first starting with the search string
var searchText = this.keyDownHistory;
var first = list.FirstOrDefault(item =>
item.Text.StartsWith(searchText, StringComparison.InvariantCultureIgnoreCase));
if (first != null)
{ /* found */
this.AssociatedObject.SelectedIndex = first.Index;
}
else
{ /* not found - so reset the KeyDownHistory */
this.keyDownHistory = string.Empty;
}
// reset the last time a key was pressed
this.LastKeyDownTime = DateTime.Now;
}
/// <summary>
/// Gets the value of the pressed key,
/// specifically converting number keys from their "Dx" value to their expected "x" value
/// </summary>
/// <param name="e"></param>
/// <returns></returns>
private static string GetKeyValue(KeyEventArgs e)
{
string rValue = string.Empty;
switch (e.Key)
{
default:
rValue = e.Key.ToString();
break;
case Key.D0:
case Key.NumPad0:
rValue = (0).ToString();
break;
case Key.D1:
case Key.NumPad1:
rValue = (1).ToString();
break;
case Key.D2:
case Key.NumPad2:
rValue = (2).ToString();
break;
case Key.D3:
case Key.NumPad3:
rValue = (3).ToString();
break;
case Key.D4:
case Key.NumPad4:
rValue = (4).ToString();
break;
case Key.D5:
case Key.NumPad5:
rValue = (5).ToString();
break;
case Key.D6:
case Key.NumPad6:
rValue = (6).ToString();
break;
case Key.D7:
case Key.NumPad7:
rValue = (7).ToString();
break;
case Key.D8:
case Key.NumPad8:
rValue = (8).ToString();
break;
case Key.D9:
case Key.NumPad9:
rValue = (9).ToString();
break;
}
return rValue;
}
/// <summary>
/// Helper class
/// </summary>
private class Item
{
public int Index;
public string Text;
}
/// <summary>
/// Helper class used for property path value retrieval
/// </summary>
private class BindingEvaluator : FrameworkElement
{
public static readonly DependencyProperty TargetProperty =
DependencyProperty.Register(
"Target",
typeof(object),
typeof(BindingEvaluator), null);
public object Target
{
get { return GetValue(TargetProperty); }
set { SetValue(TargetProperty, value); }
}
}
}

Formatting text in WinForm Label

Is it possible to format certain text in a WinForm Label instead of breaking the text into multiple labels? Please disregard the HTML tags within the label's text; it's only used to get my point out.
For example:
Dim myLabel As New Label
myLabel.Text = "This is <b>bold</b> text. This is <i>italicized</i> text."
Which would produce the text in the label as:
This is bold text. This is
italicized text.
That's not possible with a WinForms label as it is. The label has to have exactly one font, with exactly one size and one face. You have a couple of options:
Use separate labels
Create a new Control-derived class that does its own drawing via GDI+ and use that instead of Label; this is probably your best option, as it gives you complete control over how to instruct the control to format its text
Use a third-party label control that will let you insert HTML snippets (there are a bunch - check CodeProject); this would be someone else's implementation of #2.
Not really, but you could fake it with a read-only RichTextBox without borders. RichTextBox supports Rich Text Format (rtf).
Another workaround, late to the party: if you don't want to use a third party control, and you're just looking to call attention to some of the text in your label, and you're ok with underlines, you can use a LinkLabel.
Note that many consider this a 'usability crime', but if you're not designing something for end user consumption then it may be something you're prepared to have on your conscience.
The trick is to add disabled links to the parts of your text that you want underlined, and then globally set the link colors to match the rest of the label. You can set almost all the necessary properties at design-time apart from the Links.Add() piece, but here they are in code:
linkLabel1.Text = "You are accessing a government system, and all activity " +
"will be logged. If you do not wish to continue, log out now.";
linkLabel1.AutoSize = false;
linkLabel1.Size = new Size(365, 50);
linkLabel1.TextAlign = ContentAlignment.MiddleCenter;
linkLabel1.Links.Clear();
linkLabel1.Links.Add(20, 17).Enabled = false; // "government system"
linkLabel1.Links.Add(105, 11).Enabled = false; // "log out now"
linkLabel1.LinkColor = linkLabel1.ForeColor;
linkLabel1.DisabledLinkColor = linkLabel1.ForeColor;
Result:
Worked solution for me - using custom RichEditBox. With right properties it will be looked as simple label with bold support.
1) First, add your custom RichTextLabel class with disabled caret :
public class RichTextLabel : RichTextBox
{
public RichTextLabel()
{
base.ReadOnly = true;
base.BorderStyle = BorderStyle.None;
base.TabStop = false;
base.SetStyle(ControlStyles.Selectable, false);
base.SetStyle(ControlStyles.UserMouse, true);
base.SetStyle(ControlStyles.SupportsTransparentBackColor, true);
base.MouseEnter += delegate(object sender, EventArgs e)
{
this.Cursor = Cursors.Default;
};
}
protected override void WndProc(ref Message m)
{
if (m.Msg == 0x204) return; // WM_RBUTTONDOWN
if (m.Msg == 0x205) return; // WM_RBUTTONUP
base.WndProc(ref m);
}
}
2) Split you sentence to words with IsSelected flag, that determine if that word should be bold or no :
private void AutocompleteItemControl_Load(object sender, EventArgs e)
{
RichTextLabel rtl = new RichTextLabel();
rtl.Font = new Font("MS Reference Sans Serif", 15.57F);
StringBuilder sb = new StringBuilder();
sb.Append(#"{\rtf1\ansi ");
foreach (var wordPart in wordParts)
{
if (wordPart.IsSelected)
{
sb.Append(#"\b ");
}
sb.Append(ConvertString2RTF(wordPart.WordPart));
if (wordPart.IsSelected)
{
sb.Append(#"\b0 ");
}
}
sb.Append(#"}");
rtl.Rtf = sb.ToString();
rtl.Width = this.Width;
this.Controls.Add(rtl);
}
3) Add function for convert you text to valid rtf (with unicode support!) :
private string ConvertString2RTF(string input)
{
//first take care of special RTF chars
StringBuilder backslashed = new StringBuilder(input);
backslashed.Replace(#"\", #"\\");
backslashed.Replace(#"{", #"\{");
backslashed.Replace(#"}", #"\}");
//then convert the string char by char
StringBuilder sb = new StringBuilder();
foreach (char character in backslashed.ToString())
{
if (character <= 0x7f)
sb.Append(character);
else
sb.Append("\\u" + Convert.ToUInt32(character) + "?");
}
return sb.ToString();
}
Works like a charm for me!
Solutions compiled from :
How to convert a string to RTF in C#?
Format text in Rich Text Box
How to hide the caret in a RichTextBox?
Create the text as a RTF file in wordpad
Create Rich text control with no borders and editable = false
Add the RTF file to the project as a resource
In the Form1_load do
myRtfControl.Rtf = Resource1.MyRtfControlText
AutoRichLabel
I was solving this problem by building an UserControl that contains a TransparentRichTextBox that is readonly. The TransparentRichTextBox is a RichTextBox that allows to be transparent:
TransparentRichTextBox.cs:
public class TransparentRichTextBox : RichTextBox
{
[DllImport("kernel32.dll", CharSet = CharSet.Auto)]
static extern IntPtr LoadLibrary(string lpFileName);
protected override CreateParams CreateParams
{
get
{
CreateParams prams = base.CreateParams;
if (TransparentRichTextBox.LoadLibrary("msftedit.dll") != IntPtr.Zero)
{
prams.ExStyle |= 0x020; // transparent
prams.ClassName = "RICHEDIT50W";
}
return prams;
}
}
}
The final UserControl acts as wrapper of the TransparentRichTextBox. Unfortunately, I had to limit it to AutoSize on my own way, because the AutoSize of the RichTextBox became broken.
AutoRichLabel.designer.cs:
partial class AutoRichLabel
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Component Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.rtb = new TransparentRichTextBox();
this.SuspendLayout();
//
// rtb
//
this.rtb.BorderStyle = System.Windows.Forms.BorderStyle.None;
this.rtb.Dock = System.Windows.Forms.DockStyle.Fill;
this.rtb.Location = new System.Drawing.Point(0, 0);
this.rtb.Margin = new System.Windows.Forms.Padding(0);
this.rtb.Name = "rtb";
this.rtb.ReadOnly = true;
this.rtb.ScrollBars = System.Windows.Forms.RichTextBoxScrollBars.None;
this.rtb.Size = new System.Drawing.Size(46, 30);
this.rtb.TabIndex = 0;
this.rtb.Text = "";
this.rtb.WordWrap = false;
this.rtb.ContentsResized += new System.Windows.Forms.ContentsResizedEventHandler(this.rtb_ContentsResized);
//
// AutoRichLabel
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink;
this.BackColor = System.Drawing.Color.Transparent;
this.Controls.Add(this.rtb);
this.Name = "AutoRichLabel";
this.Size = new System.Drawing.Size(46, 30);
this.ResumeLayout(false);
}
#endregion
private TransparentRichTextBox rtb;
}
AutoRichLabel.cs:
/// <summary>
/// <para>An auto sized label with the ability to display text with formattings by using the Rich Text Format.</para>
/// <para>­</para>
/// <para>Short RTF syntax examples: </para>
/// <para>­</para>
/// <para>Paragraph: </para>
/// <para>{\pard This is a paragraph!\par}</para>
/// <para>­</para>
/// <para>Bold / Italic / Underline: </para>
/// <para>\b bold text\b0</para>
/// <para>\i italic text\i0</para>
/// <para>\ul underline text\ul0</para>
/// <para>­</para>
/// <para>Alternate color using color table: </para>
/// <para>{\colortbl ;\red0\green77\blue187;}{\pard The word \cf1 fish\cf0 is blue.\par</para>
/// <para>­</para>
/// <para>Additional information: </para>
/// <para>Always wrap every text in a paragraph. </para>
/// <para>Different tags can be stacked (i.e. \pard\b\i Bold and Italic\i0\b0\par)</para>
/// <para>The space behind a tag is ignored. So if you need a space behind it, insert two spaces (i.e. \pard The word \bBOLD\0 is bold.\par)</para>
/// <para>Full specification: http://www.biblioscape.com/rtf15_spec.htm </para>
/// </summary>
public partial class AutoRichLabel : UserControl
{
/// <summary>
/// The rich text content.
/// <para>­</para>
/// <para>Short RTF syntax examples: </para>
/// <para>­</para>
/// <para>Paragraph: </para>
/// <para>{\pard This is a paragraph!\par}</para>
/// <para>­</para>
/// <para>Bold / Italic / Underline: </para>
/// <para>\b bold text\b0</para>
/// <para>\i italic text\i0</para>
/// <para>\ul underline text\ul0</para>
/// <para>­</para>
/// <para>Alternate color using color table: </para>
/// <para>{\colortbl ;\red0\green77\blue187;}{\pard The word \cf1 fish\cf0 is blue.\par</para>
/// <para>­</para>
/// <para>Additional information: </para>
/// <para>Always wrap every text in a paragraph. </para>
/// <para>Different tags can be stacked (i.e. \pard\b\i Bold and Italic\i0\b0\par)</para>
/// <para>The space behind a tag is ignored. So if you need a space behind it, insert two spaces (i.e. \pard The word \bBOLD\0 is bold.\par)</para>
/// <para>Full specification: http://www.biblioscape.com/rtf15_spec.htm </para>
/// </summary>
[Browsable(true)]
public string RtfContent
{
get
{
return this.rtb.Rtf;
}
set
{
this.rtb.WordWrap = false; // to prevent any display bugs, word wrap must be off while changing the rich text content.
this.rtb.Rtf = value.StartsWith(#"{\rtf1") ? value : #"{\rtf1" + value + "}"; // Setting the rich text content will trigger the ContentsResized event.
this.Fit(); // Override width and height.
this.rtb.WordWrap = this.WordWrap; // Set the word wrap back.
}
}
/// <summary>
/// Dynamic width of the control.
/// </summary>
[Browsable(false)]
public new int Width
{
get
{
return base.Width;
}
}
/// <summary>
/// Dynamic height of the control.
/// </summary>
[Browsable(false)]
public new int Height
{
get
{
return base.Height;
}
}
/// <summary>
/// The measured width based on the content.
/// </summary>
public int DesiredWidth { get; private set; }
/// <summary>
/// The measured height based on the content.
/// </summary>
public int DesiredHeight { get; private set; }
/// <summary>
/// Determines the text will be word wrapped. This is true, when the maximum size has been set.
/// </summary>
public bool WordWrap { get; private set; }
/// <summary>
/// Constructor.
/// </summary>
public AutoRichLabel()
{
InitializeComponent();
}
/// <summary>
/// Overrides the width and height with the measured width and height
/// </summary>
public void Fit()
{
base.Width = this.DesiredWidth;
base.Height = this.DesiredHeight;
}
/// <summary>
/// Will be called when the rich text content of the control changes.
/// </summary>
private void rtb_ContentsResized(object sender, ContentsResizedEventArgs e)
{
this.AutoSize = false; // Disable auto size, else it will break everything
this.WordWrap = this.MaximumSize.Width > 0; // Enable word wrap when the maximum width has been set.
this.DesiredWidth = this.rtb.WordWrap ? this.MaximumSize.Width : e.NewRectangle.Width; // Measure width.
this.DesiredHeight = this.MaximumSize.Height > 0 && this.MaximumSize.Height < e.NewRectangle.Height ? this.MaximumSize.Height : e.NewRectangle.Height; // Measure height.
this.Fit(); // Override width and height.
}
}
The syntax of the rich text format is quite simple:
Paragraph:
{\pard This is a paragraph!\par}
Bold / Italic / Underline text:
\b bold text\b0
\i italic text\i0
\ul underline text\ul0
Alternate color using color table:
{\colortbl ;\red0\green77\blue187;}
{\pard The word \cf1 fish\cf0 is blue.\par
But please note: Always wrap every text in a paragraph. Also, different tags can be stacked (i.e. \pard\b\i Bold and Italic\i0\b0\par) and the space character behind a tag is ignored. So if you need a space behind it, insert two spaces (i.e. \pard The word \bBOLD\0 is bold.\par). To escape \ or { or }, please use a leading \.
For more information there is a full specification of the rich text format online.
Using this quite simple syntax you can produce something like you can see in the first image. The rich text content that was attached to the RtfContent property of my AutoRichLabel in the first image was:
{\colortbl ;\red0\green77\blue187;}
{\pard\b BOLD\b0 \i ITALIC\i0 \ul UNDERLINE\ul0 \\\{\}\par}
{\pard\cf1\b BOLD\b0 \i ITALIC\i0 \ul UNDERLINE\ul0\cf0 \\\{\}\par}
If you want to enable word wrap, please set the maximum width to a desired size. However, this will fix the width to the maximum width, even when the text is shorter.
Have fun!
There is an excellent article from 2009 on Code Project named "A Professional HTML Renderer You Will Use" which implements something similar to what the original poster wants.
I use it successfully within several projects of us.
Very simple solution:
Add 2 labels on the form, LabelA and LabelB
Go to properties for LabelA and dock it to left.
Go to properties for LabelB and dock it to left as well.
Set Font to bold for LabelA .
Now the LabelB will shift depending on length of text of LabelA.
That's all.
I Would also be interested in finding out if it is possible.
When we couldn't find a solution we resorted to Component Ones 'SuperLabel' control which allows HTML markup in a label.
Realising this is an old question, my answer is more for those, like me, who still may be looking for such solutions and stumble upon this question.
Apart from what was already mentioned, DevExpress's LabelControl is a label that supports this behaviour - demo here. Alas, it is part of a paid library.
If you're looking for free solutions, I believe HTML Renderer is the next best thing.
A FlowLayoutPanel works well for your problem. If you add labels to the flow panel and format each label's font and margin properties, then you can have different font styles. Pretty quick and easy solution to get working.
Yeah.
You can implements, using HTML Render.
For you see, click on the link: https://htmlrenderer.codeplex.com/
I hope this is useful.

Resources