自动TextBox宽度

时间:2012-07-11 17:59:14

标签: asp.net .net html

有一个similar thread about this。但是我想要一个具有自动宽度的多行TextBox(适合较大行的宽度)。

使用此代码,我可以使用多行TextBox(自动高度)

     <div style="float:left; white-space:nowrap ">
        <asp:TextBox style="display:inline; overflow:hidden"  
                     ID="txt1" 
                     runat="server" 
                     Wrap="false" 
                     ReadOnly="true" 
                     TextMode="MultiLine" 
                     BorderStyle="none" 
                     BorderWidth="0">
        </asp:TextBox>
    </div>
    <div style="float:left">
        <asp:TextBox ID="txt2" runat="server" Text="Example textbox"></asp:TextBox>
    </div>

代码背后:

txt1.Rows= text.Split("|").Length ' Sets number of rows but with low performance
txt1.Text = text.Replace("|", Environment.NewLine)

再次感谢您的帮助。

3 个答案:

答案 0 :(得分:2)

您可以尝试使用linq方法:

string[] rows = text.Split('|');
int maxLength = rows.Max(x => x.Length);

txt1.Rows = rows.Length;
txt1.Columns = maxLength;

答案 1 :(得分:1)

如果您愿意使用像jquery这样的插件, 你应该看一下autoresize插件。

这些也会在用户输入时调整大小。

查看一个autoresize

$(document).ready(function(){
    $('textarea').autosize();  
});

答案 2 :(得分:0)

Joel Etherton给我一个真正好的工作代码示例,说明如何使用Linq来解决这个问题,但是我不能使用Linq。

使用Linq的多行TextBox自动宽度(Joel Etherton的解决方案): C#

string[] rows = text.Split('|');
int maxLength = rows.Max(x => x.Length);

txt1.Rows = rows.Length;
txt1.Columns = maxLength;

VB

    Dim rows() As String = text.Split("|")
    Dim maxLength As Integer = rows.Max(Function(x) x.Length)
    txt1.Rows = rows.Length
    txt1.Columns = maxLength
    text = text.Replace("|", Environment.NewLine)
    txt1.Text = text

多行TextBox自动宽度解决方案2 为了实现这个“手动”,我做了这个方法来了解更大的行的长度。不是效率最高的,但它对我有用:

    Dim textRows() As String = text.Split("|")

    For Each row As String In textRows
        row = row.Trim
        textToDisplay = String.Format("{0}{1}{2}", textToDisplay, row, Environment.NewLine)
        If row.Length > maxRowLenght Then
            maxRowLenght = row.Length
        End If
    Next
    txt1.Rows = textRows.Length
    txt1.Columns = maxRowLenght
    txt1.Text = textToDisplay
相关问题