event handling in c# .net winform application which uses sql server
i have a combobox with a list of SQLusers, which have permissions granted from beforehand.
a table PERMISSION_DETAIL
with columns username
, permission_name
consists the details of permissions granted or denied
now when a user selects a SQLuser from combobox then the permissions are shown as a checkbox, like if permission is already granted, then the checkbox appears and its tick is checked, else UNCHECKED.
for this i use:
if(permission is previously granted)
checkbox1.checked = true; // here the Checkbox_CheckChanged event is called, but i dont want to call it.
checkbox1.enabled = false;
now, besides the checkbox, there is a button, on clicking it, the checkbox gets enabled, that is, to modify the permission, the user will click the button.
now the user will tick or untick the checkbox to grant or deny permission and the checkbox change event
will be called, this would be fi开发者_如何学运维ne.
i want that as the checkbox appears, its tick is automatically checked, but this calls the
checkbox_Checkchanged
event, but i dont want to call that event.
i advice you to change Checkbox_CheckChanged event to Checkbox_Click event.
private void Checkbox_Click(object sender, EventArgs e)
{
if ((sender as CheckBox).Checked)
{
MessageBox.Show("checked");
// add role to user
}
else
{
MessageBox.Show("un_checked");
/remove role ffrom user
}
}
You could check if the checkbox is enabled, before doing anything in the EventHandler:
protected void Checkbox_CheckChanged (object sender, ..EventArgs e)
{
//return if not enabled
if(!((CheckBox)sender).IsEnabled) return;
//DO THE REST
}
I think that if you make an event handler for CheckChanged, it should be called always when "check is changed", and you should handle logic thereafter.
The event is going to be called regardless, what matters is how you handle that event. An event has occurred, you can't pretend it hasn't. The only thing you can do is decide whether that event means anything to you at a particular point in time.
For example:
public void chkPermission_CheckChanged(object sender, EventArgs e)
{
bool isChecked = chkPermission.Checked;
if (this.user.HasPermission() == isChecked) { return; }
// otherwise, we need to change some permissions!
}
Analyse whether or not you need to do anything, and go from there. Don't just blindly assume something needs to change because an event fired.
Add a boolean variable, IsCheckboxEventShouldFire, to your form. Set to true initially. In the code that sets the checkbox to checked automatically, also now set IsCheckboxEventShouldFire to false. In the checkchanged event, first check if the IsCheckboxEventShouldFire is true. If it is, run your code. If not, then don't. Set IsCheckboxEventShouldFire to true at the end of the event's code.
精彩评论