Reputation: 219
Does disabling a button during execution of its OnClick event cause its intended action to be undone?
If so, what's a good way of disabling it after execution of the event? If not, what could adding button.Enabled = false
be doing to cause my form to essentially "forget" what it was doing?
Edited to include code:
Basically, I have a delete button (Button deleteButton
) that, when pressed, calls another function (DeleteRow
) that deletes a row from a DataTable (tbl
) bound to a ComboBox (selector
).
deleteButton_Click(object sender, EventArgs e)
{
DeleteRow(selector.SelectedIndex);
}
DeleteRow(index)
{
tbl.Rows[index].Delete();
selector.DisplayMember = "text";
selector.ValueMember = "id";
selector.DataSource = tbl;
selector.SelectedIndex = 0;
deleteButton.Enabled = false;
}
With the deleteButton.Enabled = false
in the code, nothing is changed in the DataTable or the ComboBox. When that code is removed, however, everything works as intended with the exception of deleteButton
remaining enabled.
Upvotes: 0
Views: 80
Reputation: 11957
Well, as usual a nice little example proves or disproves the theory.
With a new .Net4.0 Winforms Application in VS2010 C# Express, I added a combobox and a button to a form. On clicking the button, the current item is removed from the combobox and the button gets disabled. Try it out.
using System;
using System.Data;
using System.Windows.Forms;
namespace WF_ButtonDisabling
{
public partial class Form1 : Form
{
DataTable _dt = new DataTable();
public Form1()
{
InitializeComponent();
SetupDataTable();
CreateData();
BindCombobox();
}
void SetupDataTable()
{
_dt.Columns.Add("Name", typeof(string));
_dt.Columns.Add("Age", typeof(int));
}
void CreateData()
{
DataRow dr = _dt.NewRow();
dr.SetField("Name", "Fred"); dr.SetField("Age", 45);
_dt.Rows.Add(dr);
dr = _dt.NewRow();
dr.SetField("Name", "John"); dr.SetField("Age", 42);
_dt.Rows.Add(dr);
dr = _dt.NewRow();
dr.SetField("Name", "Tom"); dr.SetField("Age", 49);
_dt.Rows.Add(dr);
}
void BindCombobox()
{
comboBox1.DisplayMember = "Name";
comboBox1.ValueMember = "Age";
comboBox1.DataSource = _dt;
comboBox1.SelectedIndex = 0;
}
void button1_Click(object sender, EventArgs e)
{
DeleteRow(comboBox1.SelectedIndex);
}
void DeleteRow(int index)
{
_dt.Rows[index].Delete();
BindCombobox();
button1.Enabled = false;
}
}
}
Upvotes: 1
Reputation: 224904
Does disabling a button during execution of its OnClick event cause its intended action to be undone?
No, it doesn't. There's a little bit of a logical paradox otherwise. button.Enabled = false;
is fine, and it's not causing your form to forget what it was doing. The problem is something else.
Upvotes: 2