adl
adl

Reputation: 2045

How to add text to a textbox and treat it as a block of text?

I want a textbox that it is possible to add "text blocks" to it. The definition of a "text block" is:

I have a DataGridView with a CellClick event attached to it. I want that when the CellClick event is occurs, the content of the cell will be placed in a textbox and will be considered as a text block. The location of the added block will be in the carot position of the textbox or at the end of the textbox if the textbox is not focused and thus the carot is not blinking.

I also want that the textbox could function as a normal textbox, meaning that the user can add or delete any chars/text he want excepts the text blocks that they must be added/deleted completely as defined above.

Maybe I need to use some other GUI controls except textbox to accomplish this mission, I don't know.

I thought about some solutions but I don't know which is the best (maybe none of them): (remark: each of the following solutions assumes that there is an KeyPress event attached)

  1. Adding hidden characters (if possible) before and after each block to mark it.
  2. Creating a list of objects which represents all the text blocks, each object containing two fiels: startIndex, endIndex. Not so good because adding or deleting chars from the textbox requires to update all the indexes of the blocks located after the added/deleted chars by +1 or -1 for each char.
  3. Creating a list of objects which represents all the text in the textbox, each object containing two fields: text, flag. Each time a char is added manually or a word is added by the event, an object is added to the list and the object's text field is set to the added chars, and the object's flag filed is set to true if the chars are a word added by the event, or false otherwise.
  4. Splitting the textbox to 2 parts and creating a small textbox between them for each text block added by the event, and treating the small textbox diffetently. When the text in the small textbox is deleted the whole textbox control is deleted and the splited textbox is united. Doesn't sounds me so good.

What is the best way to implement this?

Thanks!

Upvotes: 2

Views: 496

Answers (1)

Tergiver
Tergiver

Reputation: 14517

I have never seen a control with this behavior. I'm not saying that someone hasn't written one, just that it's unlikely. This means that you're going to have to build it.

If you've never created a custom control, search the web for "creating custom winforms controls" or similar. You first need to understand the basic techniques.

Then you're going to want to know how to store the underlying text for editing. You can start by learning some of the techniques commonly used for standard text-editing controls. Pick one that you can modify for your custom scenario. Here are a few off the top of my head:

Gap Buffer

Rope

Piece Chains

Good luck!

Upvotes: 1

Related Questions