atabrizi
atabrizi

Reputation: 918

Dont delete from texbox ,only add some text to it in c#

I have a Textbox in my windows form project. that show comments of users. I want when this form show, this Textbox fill from database and user can't delete text of that. they can only add some text to it. how can I do this?

Upvotes: 0

Views: 2244

Answers (3)

Syed Ali Taqi
Syed Ali Taqi

Reputation: 4974

According to me best solution would be using disbaled textbox as it would be difficult to capture keydown or text_changed event and will also require AutoPostBack.

 <asp:TextBox ID="TextBox1" runat="server" Enabled="false"></asp:TextBox>
 <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>

Code

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;
}

Also in the comments @afaolek stated the same solution.

Upvotes: 1

Mohammad Mirmostafa
Mohammad Mirmostafa

Reputation: 1775

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;
}

Upvotes: 0

Hamix
Hamix

Reputation: 1335

Adapting from Hans Passant's Button inside a winforms textbox answer and Add label inside textbox control:

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;
      }
    }

Set database value as LabelText.

var txt=new TextBoxWithLabel {LabelText=dbVal};

Upvotes: 0

Related Questions