[英]Dont delete from texbox ,only add some text to it in c#
我的Windows窗體項目中有一個文本框。 顯示用戶評論。 我想在顯示此表單時,從數據庫填充此文本框,而用戶不能刪除該文本。 他們只能向其中添加一些文本。 我怎樣才能做到這一點?
據我最好的解決辦法是使用disbaled
文本框,因為這將是很難捕捉到keydown
或text_changed
事件,也將需要AutoPostBack
。
<asp:TextBox ID="TextBox1" runat="server" Enabled="false"></asp:TextBox>
<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
碼
protected void Page_Load(object sender, EventArgs e)
{
TextBox1.Text = "OriginalContent "; // as example
}
protected void Button1_Click(object sender, EventArgs e)
{
String text = TextBox1.Text + TextBox2.Text;
}
@afaolek還在評論中指出了相同的解決方案。
改編自winforms文本框答案中的Hans Passant 按鈕,並在文本框控件中添加標簽 :
public class TextBoxWithLabel : TextBox {
[DllImport("user32.dll")]
private static extern IntPtr SendMessage(IntPtr hWnd, int msg, IntPtr wp, IntPtr lp);
Label label = new Label();
public TextBoxWithLabel() {
label.BackColor = Color.LightGray;
label.Cursor = Cursors.Default;
label.TextAlign = ContentAlignment.MiddleRight;
this.Controls.Add(label);
}
private int LabelWidth() {
return TextRenderer.MeasureText(label.Text, label.Font).Width;
}
public string LabelText {
get { return label.Text; }
set {
label.Text = value;
SendMessage(this.Handle, 0xd3, (IntPtr)2, (IntPtr)(LabelWidth() << 16));
OnResize(EventArgs.Empty);
}
}
protected override void OnResize(EventArgs e) {
base.OnResize(e);
int labelWidth = LabelWidth();
label.Left = this.ClientSize.Width - labelWidth;
label.Top = (this.ClientSize.Height / 2) - (label.Height / 2);
label.Width = labelWidth;
label.Height = this.ClientSize.Height;
}
}
將數據庫值設置為LabelText。
var txt=new TextBoxWithLabel {LabelText=dbVal};
private string current;
private void TextBox_OnTextChanged(object sender, TextChangedEventArgs e)
{
if (string.IsNullOrEmpty(this.current))
{
this.current = this.TextBox.Text;
return;
}
if (!this.TextBox.Text.Contains(this.current))
this.TextBox.Text = this.current;
else
this.current = this.TextBox.Text;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.