Monday, September 10, 2007

How to write custom TextBox

namespace StringEdit
{
public partial class StriingEdit : TextBox
{



Boolean isMandatory;
Boolean allowNegative;

ErrorProvider error = new ErrorProvider();

public Boolean AllowNegative
{
get { return allowNegative; }
set { allowNegative = value; }
}



public Boolean IsMandatory
{
get { return isMandatory; }
set { isMandatory = value; }
}
public StriingEdit()
{
InitializeComponent();

}

protected override void OnValidating(CancelEventArgs e)
{


if (this.isMandatory && this.Text == String.Empty)
{
error.SetError(this, ErrorMessage.EmptyTextBox);
MessageBox.Show(ErrorMessage.EmptyTextBox);
}

else if (allowNegative)
{
try
{
if (Single.Parse(this.Text) <= 0)
{
error.SetError(this, ErrorMessage.TextBoxNegValue);
MessageBox.Show(ErrorMessage.TextBoxNegValue);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
base.OnValidating(e);
error.Clear();



}

}
}


namespace StringEdit
{
public class ErrorMessage
{
private static string emptyTextBox = "TextBox is empty";
private static string textBoxNegValue = "Value should greater or equal to zero";

public static string EmptyTextBox
{
get { return ErrorMessage.emptyTextBox; }

}
public static string TextBoxNegValue
{
get { return ErrorMessage.textBoxNegValue; }

}
}
}

for complete running code for this project mail at huzaifa.shabbir@yahoo.com

No comments: