自动调整文本框宽度

4

有一个类似的主题。但是我想要一个多行文本框,它可以自动调整宽度(根据更大行自适应宽度)。

使用这段代码可以实现多行文本框(自动高度):

     <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个回答

3
你可以尝试使用LINQ方法:

你可以尝试使用LINQ方法:

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

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

1

如果您愿意使用像jquery这样的插件,您应该看一下自动调整大小插件。

这些插件将随着用户的输入而调整大小。

查看一个autoresize

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

0

Joel Etherton给了我一个使用Linq解决此问题的真正好的工作代码示例,但不幸的是我不能使用Linq。

使用Linq自动调整多行文本框宽度(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

多行文本框自动宽度解决方案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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接