日期:2014-05-17  浏览次数:20856 次

怎么样更改多行文本框某一行的文本
文本框中事实上有多行内容,我这样想改变第一行的文本,没一点用,也不报错,为何?有啥办法?

C# code
this.textBox1.Lines[0]=System.DateTime.Now.ToString() ;


------解决方案--------------------
老问题了。
string[] lines = this.textBox1.Lines;
lines[0]=System.DateTime.Now.ToString();
this.textBox1.Lines = lines;

原因是lines属性get返回的是一个string数组,你修改这个并不影响Text,而set方法则会重新赋值给Text
------解决方案--------------------
文本框中事实上有多行内容,我这样想改变第一行的文本,没一点用,也不报错,为何?有啥办法?

为什么不报错么?
当然不报错了。
C# code

[Localizable(true), SRDescription("TextBoxLinesDescr"), Editor("System.Windows.Forms.Design.StringArrayEditor, System.Design, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", typeof(UITypeEditor)), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), MergableProperty(false), SRCategory("CatAppearance")]
public string[] Lines
{
    get
    {
        int num2;
        string text = this.Text;
        ArrayList list = new ArrayList();
        for (int i = 0; i < text.Length; i = num2)
        {
            num2 = i;
            while (num2 < text.Length)
            {
                char ch = text[num2];
                if ((ch == '\r') || (ch == '\n'))
                {
                    break;
                }
                num2++;
            }
            string str2 = text.Substring(i, num2 - i);
            list.Add(str2);
            if ((num2 < text.Length) && (text[num2] == '\r'))
            {
                num2++;
            }
            if ((num2 < text.Length) && (text[num2] == '\n'))
            {
                num2++;
            }
        }
        if ((text.Length > 0) && ((text[text.Length - 1] == '\r') || (text[text.Length - 1] == '\n')))
        {
            list.Add("");
        }
        return (string[]) list.ToArray(typeof(string));//返回的是当前文本按回车换行分割出来的一个string 数组,是text的副本,你可以修改这个数组的数据,不影响text,也不报错。很正常,你并没有设置控件
    }
    set
    {
        if ((value != null) && (value.Length > 0))
        {
            StringBuilder builder = new StringBuilder(value[0]);
            for (int i = 1; i < value.Length; i++)
            {
                builder.Append("\r\n");
                builder.Append(value[i]);
            }
            this.Text = builder.ToString();//看到了么,这里对Text进行了设置
        }
        else
        {
            this.Text = "";
        }
    }
}

------解决方案--------------------

string[] lines = this.textBox1.Lines;
lines[0]=System.DateTime.Now.ToString();
this.textBox1.Lines = lines;
------解决方案--------------------
探讨
请问6楼你这段代码是从哪里反编译出来的吗,我怎么不能像像看MFC中源代码那样看到这种代码?