visual usar texto seleccionar eventos escribir cuadro control como capturar c# textbox resize

c# - usar - Autoresize el control de cuadro de texto verticalmente



textbox control c# (6)

Podría anclarlo en la parte inferior, eso asegurará que el cuadro de texto se redimensiona verticalmente cuando se cambia el tamaño de la forma a la que pertenece. Además, un cuadro de texto que cambie su tamaño puede que no sea una cosa elegante, ya que podría alterar la forma en que se muestran otros componentes. ¿Por qué no le das un tamaño máximo en lugar de cambiar el tamaño?

En un formulario C #, tengo un panel anclado en todos los lados, y adentro, un cuadro de texto, anclado arriba / izquierda / derecha.

Cuando el texto se carga en el cuadro de texto, quiero que se expanda automáticamente verticalmente para que no tenga que desplazar el cuadro de texto (desplazar el panel como máximo, si hay más texto que no se ajusta al panel). ¿hay alguna manera de hacer esto con un cuadro de texto? (No estoy obligado a usar este control, así que si hay otro control que se ajuste a la descripción, no dude en mencionarlo)


Puede usar una etiqueta y establecer AutoSize en true .


Sugeriría usar Graphics.MeasureString .

Primero crea un objeto Graphics , luego llama MeasureString en él, pasando la cadena y la fuente del cuadro de texto.

Ejemplo

string text = "TestingTesting/nTestingTesting/nTestingTesting/nTestingTesting/n"; // Create the graphics object. using (Graphics g = textBox.CreateGraphics()) { // Set the control''s size to the string''s size. textBox.Size = g.MeasureString(text, textBox.Font).ToSize(); textBox.Text = text; }

También puede limitarlo al eje vertical configurando solo la propiedad MeasureString y utilizando la sobrecarga MeasureString que también acepta el int width .

Editar

Como señaló SLaks, otra opción es usar TextRenderer.MeasureString . De esta forma, no es necesario crear un objeto Graphics .

textBox.Size = TextRenderer.MeasureString(text, textBox.Font).ToSize();

Aquí podría limitar el cambio de tamaño vertical utilizando la técnica de Hans, pasando un parámetro de Size adicional a MeasureString con la altura int.MaxValue .


Pruebe este enfoque:

código aspx.cs

protected int GetRows(object value) { if (value == null || string.IsNullOrWhiteSpace(value.ToString())) return 1; var contentTrimmed = value.ToString().Replace(''/t'', '' '').Replace(''/r'', '' '').Replace(''/n'', '' '').Trim(); var length = (decimal)contentTrimmed.Length; if (length == 0) return 1; int res = 0; decimal maxLength = 56; using (System.Drawing.Graphics graphics = System.Drawing.Graphics.FromImage(new Bitmap(1, 1))) { SizeF sizeRef = graphics.MeasureString("W", new Font("Segoe UI", 13, FontStyle.Regular, GraphicsUnit.Pixel)); maxLength = maxLength * (decimal)sizeRef.Width; SizeF size = graphics.MeasureString(contentTrimmed, new Font("Segoe UI", 13, FontStyle.Regular, GraphicsUnit.Pixel)); length = (decimal)size.Width; } res = (int)Math.Round(length / (decimal)maxLength, MidpointRounding.AwayFromZero); if (res == 0) return 1; return res; }

código aspx

<asp:TextBox ID="txtValue" TextMode="MultiLine" Text=''<%# Eval("Value") %>'' runat="server" MaxLength="500" Width="700px" Rows=''<%# GetRows(Eval ("Value")) %>'' ></asp:TextBox>


Asumiré que es un cuadro de texto multilínea y que permitirá que crezca verticalmente. Este código funcionó bien:

private void textBox1_TextChanged(object sender, EventArgs e) { Size sz = new Size(textBox1.ClientSize.Width, int.MaxValue); TextFormatFlags flags = TextFormatFlags.WordBreak; int padding = 3; int borders = textBox1.Height - textBox1.ClientSize.Height; sz = TextRenderer.MeasureText(textBox1.Text, textBox1.Font, sz, flags); int h = sz.Height + borders + padding; if (textBox1.Top + h > this.ClientSize.Height - 10) { h = this.ClientSize.Height - 10 - textBox1.Top; } textBox1.Height = h; }

Debería hacer algo razonable cuando el cuadro de texto está vacío, como establecer la propiedad MinimumSize.


La respuesta seleccionada actual NO maneja líneas sin espacios como "jjjjjjjjjjjjjjjjjjjj" x1000 (piense en lo que sucedería si alguien pega una URL)

Este código resuelve ese problema:

private void txtBody_TextChanged(object sender, EventArgs e) { // amount of padding to add const int padding = 3; // get number of lines (first line is 0, so add 1) int numLines = this.txtBody.GetLineFromCharIndex(this.txtBody.TextLength) + 1; // get border thickness int border = this.txtBody.Height - this.txtBody.ClientSize.Height; // set height (height of one line * number of lines + spacing) this.txtBody.Height = this.txtBody.Font.Height * numLines + padding + border; }