Reputation: 45
I have created a custom textbox which only allows numbers but when I use the control on my page I am unable to increase its width. I tried to set the autosize property the control to TRUE but no luck.
The code of the custom text box is mentioned below
public partial class NumericalTextBox : UserControl
{
public NumericalTextBox()
{
InitializeComponent();
textBox1.KeyPress += NumericalTextBox_KeyPress;
}
private void NumericalTextBox_KeyPress(object sender, KeyPressEventArgs e)
{
if ((int)(e.KeyChar) == 22)
{
IDataObject clipData = Clipboard.GetDataObject();
string dataSet = (string)clipData.GetData(DataFormats.Text);
foreach (char data in dataSet)
{
if (!(char.IsNumber(data)) && !(char.IsControl(data)))
{
e.Handled = true;
return;
}
}
return;
}
else
{
if (((char.IsNumber(e.KeyChar))) || ((char.IsControl(e.KeyChar))))
{
return;
}
}
e.Handled = true;
}
}
Can someone help me on how to enable resizing of the text Box.
Upvotes: 0
Views: 956
Reputation: 3317
Did you set the textbox1 to anchor with the size of the usercontrol? If not it resizes only the NumericalTextBox but not the actual textbox contained in the usercontrol.
textBox1.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
If the textbox is the only control you could also just set the dockstyle to fill:
textBox1.Dock = System.Windows.Forms.DockStyle.Fill;
The textbox will then automatically enlarge to fill the available space in the usercontrol.
As mentionend in the comments of your question, the correct way to implement a NumericTextbox would be to actually inherit from TextBox
itself and put your handling code in there. TextBox is not a sealed class so I don't see any reasons to not inherit directly from there.
Upvotes: 2
Reputation: 596
For the custom control set AutoSize to false and maximum height to 20 (same as Textbox Height) For the textbox set Dock to Fill
Upvotes: 0