I have made a Custom TextBox that is a panel with a TextBox inside.
What i'm trying to do is [CustomTextBox name].SelectAll();
where it
returns [TextBox nameInsideCustomControl].SelectAll();
[...]
is just a name.
How can i implement it?
I have tried:
[Category("Custom")]
public void SelectAll
{
get { textBox1.SelectAll(); }
}
But i don't think it's right.
Answer:
public void SelectAll() => textBox1.SelectAll();
. It's a method, not a property. –
dr.null
You have a CustomTextBox
that inherits from Panel
and you want to be able to select all text in the TextBox
that it contains.
To achieve this objective, first make sure that your CustomTextBox
exposes a pubic method named SelectAll
that forwards the command to the private TextBox
it contains. But in addition to that you will either need to make sure that the internal TextBox
receives focus or set the HideSelection
property of the internal TextBox
to false
. Otherwise you may still not see the selection highlighted.
Custom Text Box example
public partial class CustomTextBox : Panel
{
public void SelectAll()
{
textBox1.SelectAll();
// Ensure text box gets the focus.
textBox1.Focus();
}
public void LoadTestData() =>
textBox1.Text = "Don't forget to give Focus to the TextBox!";
public CustomTextBox()
{
BackColor= Color.Azure;
label1 = new System.Windows.Forms.Label();
textBox1 = new System.Windows.Forms.TextBox();
#region I N I T I A L I Z E
SuspendLayout();
label1.AutoSize = true;
label1.Location = new System.Drawing.Point(12, 17);
label1.Size = new System.Drawing.Size(143, 25);
label1.TabIndex = 0;
label1.Text = "Custom Text Box";
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)));
textBox1.Location = new System.Drawing.Point(190, 17);
textBox1.Multiline = true;
textBox1.Size = new System.Drawing.Size(206, 126);
textBox1.TabIndex = 1;
textBox1.HideSelection = false;
Controls.Add(textBox1);
Controls.Add(label1);
Name = "CustomTextBox";
Size = new System.Drawing.Size(424, 157);
ResumeLayout(false);
PerformLayout();
#endregion I N I T I A L I Z E
}
private Label label1;
private TextBox textBox1;
}
Minimal Test Code
public partial class MainForm : Form
{
public MainForm()
{
InitializeComponent();
customTextBoxPanel.LoadTestData();
buttonSelectAllTest.Click += onClickSelectAllTest;
}
private void onClickSelectAllTest(object? sender, EventArgs e)
{
customTextBoxPanel.SelectAll();
}
}