BlueSky
BlueSky

Reputation: 5

How can I reset my form in C#?

I have a form (in C#) which consists of buttons, picture boxes, labels that show information to users, and a combobox that the users can select data.

How can I add a refresh button that causes all my form changes to revert to their initial state when clicked? More specifically, how can I write a function that updates the form to have no data selected and initialized fields?

Upvotes: 0

Views: 209

Answers (3)

SHM
SHM

Reputation: 1952

if you are not loading default state of your control from a database or any thing like that you can reset it easily for example you can do this for a combobox:

this.comboBox.ResetText();

but if you are loading default state from a datasource i suggest you use Tag property of your control, its type is object. i mean you should store default state of your control in Tag Property and when you want to restore that just cast Tag Proprty to what ever you want. see:

this.comboBox.Tag = myState;

and when you want to retrieve it:

MyClass class = (MyClass)this.comboBox.Tag;

or this.comboBox.Items.Add(this.comboBox.Tag);

there you go. tell me if you need more explain :)

Upvotes: 0

mason
mason

Reputation: 32693

Markup

<asp:TextBox runat="server" id="TextBox1" />
<asp:Button id="ResetBtn" OnClick="ResetBtn_Click" Text="Reset Form!" />

Code Behind

protected void Page_Load(object sender, EventArgs e)
{
    if(!IsPostBack)
    {
        TextBox1.Text="Some random text";
    }
}

protected void ResetBtn_Click(object sender, EventArgs e)
{
    TextBox1.Text="";
}

When the user clicks the button, you can set the value of the text box to whatever you want. In this case, empty.

Upvotes: 0

dhrumilap
dhrumilap

Reputation: 142

Use data bindings to bind your object to the form's controls. So by resetting the databound object to null all your controls on the form will be reset.

Here are some helpful links:

A Detailed Data Binding Tutorial

Data binding concepts in .NET windows forms

Upvotes: 1

Related Questions