athom
athom

Reputation: 1277

Is there a way to dynamically copy controls and their event handlers on a form?

So here's the meat of what I want to accomplish: I have a rich textbox called txtNotes and two buttons to either save or delete. When save is clicked, the text in the rich textbox will be saved to a database (not an issue), and a new rich textbox and buttons will appear below which will act the same as previously. The delete button would remove those controls from the form and the info from the database. The user should hypothetically be able to save and create an ulimited number of notes.

I have no idea if this is possible or if I'm thinking about this in completely the wrong way. If you have any good solutions for me, I would greatly appreciate it.

Upvotes: 0

Views: 1603

Answers (3)

ispiro
ispiro

Reputation: 27713

Try something like this:

public Form1()
{
    InitializeComponent();
    Controls.Add(CreateBox(0, 0));
    AutoScroll = true;
}

Panel CreateBox(int X, int Y)
{
    Panel panel = new Panel();
    panel.Location = new Point(X, Y);
    panel.Size = new Size(100, 150);

    RichTextBox rtb = new RichTextBox();
    panel.Controls.Add(rtb);

    Button b = new Button();
    b.Location = new Point(10, 100);
    b.Tag = rtb;
    b.Click += AllButtons_Click;
    panel.Controls.Add(b);

    return panel;
}

int i = 0;
void AllButtons_Click(object sender, EventArgs e)
{
    ((RichTextBox)((sender as Button).Tag)).Text = "Clicked";
    i += 150;
    Controls.Add(CreateBox(0, i));
}

Although I'm getting some strange behavior from the AutoScroll.

Upvotes: 0

DIXONJWDD
DIXONJWDD

Reputation: 1286

That seems like it could get out of hand, and is extremely complex.

If you have a text box to allow the user to enter text and a button to save, why not use a listView or something similar, which could show the user what has been added to the database and then allow them to select items and delete them as they wish.

This control will be much more manageable and easily scrollable to take your "unlimited" number of entries.

You'll need to get a list of selected items in the listView to delete on deleteButton_Click event, then use this list to iteratively delete all of the items from your database.

Hope that's helpful.

Upvotes: 2

Sam Axe
Sam Axe

Reputation: 33738

Encapulating the RTB and Buttons in a UserControl seems like a good place to start.

Then you create a TextSaveRequested(Object sender, TextEventArgs e) event that is fired from the save button, and simply Dispose() the control when the delete is pressed (along with the related database activity, perhaps a TextDeleteRequested event).

Upvotes: 1

Related Questions