string <-> int/float conversion pain in .net winform
the Text property of control on winform is always string type, so if i wanna expose property of other type for custom control, i have to do the conversion as following, if i have dozens of properties to expose, it will be such pain for me.
public int ImageGroupLength
{
get
{
return int.Parse(this.imageGroupLength.Text);
}
set
{
this.imageGroupLength.Text = value.ToString();
}
}
so, is there any elegant way to 开发者_开发问答do the conversion?
Creating your own control is the way to go here. Add a new class to your project and paste the code shown below. Compile. The new control shows up on the top of your toolbox. You'll want to implement the BadValue event to warn the user that the entered text isn't suitable. And the ValueChanged is available to get an event when the Value property changes.
using System;
using System.Windows.Forms;
class ValueBox : TextBox {
public event EventHandler BadValue;
public event EventHandler ValueChanged;
private int mValue;
public int Value {
get { return mValue; }
set {
if (value != mValue) {
mValue = value;
OnValueChanged(EventArgs.Empty);
base.Text = mValue.ToString();
}
}
}
protected void OnValueChanged(EventArgs e) {
EventHandler handler = ValueChanged;
if (handler != null) handler(this, e);
}
protected void OnBadValue(EventArgs e) {
EventHandler handler = BadValue;
if (handler != null) handler(this, e);
}
protected override void OnHandleCreated(EventArgs e) {
base.OnHandleCreated(e);
base.Text = mValue.ToString();
}
protected override void OnValidating(System.ComponentModel.CancelEventArgs e) {
int value;
if (!int.TryParse(base.Text, out value)) {
SelectionStart = 0;
SelectionLength = base.Text.Length;
e.Cancel = true;
OnBadValue(EventArgs.Empty);
}
else base.OnValidating(e);
}
}
Have you considered subclassing the TextBox control and simply placing that on your custom control instead? You could create a new property that parses the input string and returns an integer.
Not exactly, but you can at-least get some safety in there by using something like this. This will save you heart-ache when people try and put text into the length field!
public int ImageGroupLength
{
get
{
int ret;
int.TryParse(this.imageGroupLength.Text, out ret);
return ret; //Ret will be 0 if tryparse fails
}
set
{
...
}
}
精彩评论