Why is checkbox state in CheckChanged handler always true - c#

I have a checkbox that I have declared in the following manner
checkbox = new CheckBox();
checkbox.ID = "AreaGroup";
checkbox.AutoPostBack = true;
checkbox.CheckedChanged += new System.EventHandler(this.EHArea_Clicked);
I then declare the EHArea_Clicked function in the code behind with the following method
void EHArea_Clicked(Object sender, EventArgs e)
{
foreach (RepeaterItem aItem in Repeater1.Items)
{
checkbox = (CheckBox)aItem.FindControl("TownCheckbox");
if (((CheckBox)sender).Checked)
{
checkbox.Checked = true;
}
else
{
checkbox.Checked = false;
}
}
}
The problem I have is that
((CheckBox)sender).Checked
Always evaluates to true regardless of if I am checking or unchecking the checkbox. Does anyone have an idea as to why this is happening?

I believe your prolbem is that you are reusing the checkbox variable. You need a new variable. Try something like this. Also you can reduce the if else to one line.
void EHArea_Clicked(Object sender, EventArgs e)
{
foreach (RepeaterItem aItem in Repeater1.Items)
{
CheckBox currentCheckBox = (CheckBox)aItem.FindControl("TownCheckbox");
currentCheckBox.Checked = ((CheckBox)sender).Checked;
}
}

Related

ComboBox SelectedIndexChanged always fired/triggered even disabled

I got two comboxBox with SelectedIndexChanged event enabled.
In the comboBox2 i want to change the SelectedValue of comboBox1, and that works, but the SelectedIndexChanged of comboBox1 is always triggered even i explicit disabled that.
And the code in selectedIndexChange of the ComboBox1 overwrite what I do in the ComboBox2, that the problem.
I've tried hundreds ways to avoid that but anything works, the event always occurs.
Bellow is my code of ComboBox1:
private void cmbBeneficiario_SelectedIndexChanged(object sender, EventArgs e)
{
ComboBox cb = (ComboBox)sender;
if (!cb.Focused)
{
return;
}
systemChange = true;
if (cnpjChange)
{
if (!string.IsNullOrWhiteSpace(cmbBeneficiario.Text) &&
!string.IsNullOrWhiteSpace(cmbBeneficiario.Text))
{
var beneficiarioApoliceBeneficiario =
averbacaoController.GetApoliceBeneficiario(cmbBeneficiario.Text);
var apolices = beneficiarioApoliceBeneficiario.Select(x => x.numero_apolice).ToList();
cmbApolice.DataSource = apolices;
cmbApolice.DisplayMember = "numero_apolice";
cmbApolice.Invalidate();
Refresh();
cmbApolice_SelectedIndexChanged(this, e);
var listBene = beneficiariosList;
var filteredList = listBene.Where(x => x.nome_beneficiario == cmbBeneficiario.Text).ToList();
cbbCNPJBeneAverb.DisplayMember = "cnpj_beneficiario";
cbbCNPJBeneAverb.DataSource = filteredList;
}
CarregaBeneficiarioPerfil();
systemChange = false;
}
}
The comboBox2 code (note that I disabled the event of combobox1):
private void cbbCNPJBeneAverb_SelectedIndexChanged(object sender, EventArgs e)
{
cnpjChange = true;
ComboBox cb = (ComboBox)sender;
if (!cb.Focused)
{
return;
}
Console.WriteLine($#"Old ID {cmbBeneficiario.SelectedValue}");
var beneficiario = averbacaoController.GetBeneficarioByCNPJ(cbbCNPJBeneAverb.Text, cmbBeneficiario.Text);
cmbBeneficiario.SelectedIndexChanged -= new EventHandler(cmbBeneficiario_SelectedIndexChanged);
if (cbbCNPJBeneAverb.SelectedIndex > -1)
{
cmbBeneficiario.SelectedValue = beneficiario.id_beneficiario;
CarregaBeneficiarioPerfil();
}
Console.WriteLine($#"New ID {cmbBeneficiario.SelectedValue}");
Console.WriteLine($#"Tinha que ser o ID {beneficiario.id_beneficiario}");
cmbBeneficiario.SelectedIndexChanged += new EventHandler(cmbBeneficiario_SelectedIndexChanged);
cnpjChange = false;
}
Printscreen of my debug:
As my comments above, you can use a class-scope variable to do check:
Add a temporary class-scope variable:
private bool cb1EventIgnore = false;
Set it to ture/false in cbbCNPJBeneAverb_SelectedIndexChanged:
if (cbbCNPJBeneAverb.SelectedIndex > -1)
{
cb1EventIgnore = true;
cmbBeneficiario.SelectedValue = beneficiario.id_beneficiario;
CarregaBeneficiarioPerfil();
cb1EventIgnore = false;
}
Check the value cb1EventIgnore in cmbBeneficiario_SelectedIndexChanged at the beginning:
private void cmbBeneficiario_SelectedIndexChanged(object sender, EventArgs e)
{
if(cb1EventIgnore) return;
//your codes here
}
After a lot of attempts, bellow are the piece of code that solved my question:
cmbBeneficiario.Enabled = false;
Simple like this, i dont know why c# was not able to not trigger the event even I explicit told him to.

How to get checked checkbox value which is created dynamically in button click event

i am having checkboxes which are created dynamically in page_load event and put it in panel.
foreach (DataRow dr in column_ds.Rows)
{
column_checkbox = new CheckBox();
column_checkbox.Text = (string)dr["COLUMN_NAME"];
columnpanel1.Controls.Add(column_checkbox);
}
now i want the checked check box values in btn_click event.
any ideas?
i tried,
columnpanel1.FindControl("column_checkbox");
and
CheckBox cb=(CheckBox)FindControl("column_checkbox");
if (column_checkbox.Checked) { }
{
string name = column_checkbox.Text;
}
On click event of button, you can implement below logic.
protected void btn_click(object sender, EventArgs e)
{
foreach(var row in columnpanel1.Rows)
{
var tempchkBx= row.Controls[0] as CheckBox;
if(tempchkBx.IsChecked)
{
//write your code
}
}
}
You should do this
foreach (DataRow dr in column_ds.Rows)
{
column_checkbox = new CheckBox();
column_checkbox.Text = (string)dr["COLUMN_NAME"];
column_checkbox.ID = (string)dr["ID"]
columnpanel1.Controls.Add(column_checkbox);
}
Than you can find control using ID.
Thank you for all your comments and answers.
Finally i got by,
foreach (Control cb in columnpanel1.Controls)
{
if (cb is CheckBox)
{
CheckBox c = (CheckBox)cb;
if (c.Checked)
{
string s = c.Text;
}
}
}
You can also do this in LINQ:
var boxes = columnpanel1.Controls.OfType<CheckBox>().Where(c=>c.Checked).ToList();
foreach(var chk in boxes )
{
string s = chk.Text;
}
In case for that to work you need to add an event handler to dynamically added controls in your case
checkbox = new CheckBox();
phChecklist.Controls.Add(checkbox);
checkbox.CheckedChanged += checkBox_CheckedChanged;
and then what you need to do in the method
private void CheckBox_CheckedChanged(object sender, System.EventArgs e)
{
...
}

Checkbox Checked Event for multiple dynamic Checkboxes

I have an aspx page where I dynamically create checkboxes and add them to a panel from data in a SQL database. I need to have only one checkbox checked at a time. I have tried and googled just about everything but I cannot get the right answer. How would I go about getting that done.
My code for creating the checkboxes
public void CreateTimeSelection()
{
DataSet times = GetTimes();
int i = 0;
foreach (DataTable table in times.Tables)
{
foreach (DataRow row in table.Rows)
{
CheckBox chkTime = new CheckBox();
i += 1;
chkTime.ID = row["Time"].ToString();
chkTime.AutoPostBack = true;
chkTime.Text = row["Time"].ToString();
chkTime.CheckedChanged += new EventHandler(this.CheckChanged_click);
pnlTimeSlots.Controls.Add(chkTime);
pnlTimeSlots.Controls.Add(new LiteralControl("<br />"));
}
}
}
Code for Checkbox event handlers
protected void CheckChanged_click(object sender, EventArgs e)
{
CheckBox chkSelect = (CheckBox)sender;
if (chkSelect.Checked == true)
{
//set other checkboxes to false
}
}

How do i use the checkBox2 to check if its checked or not?

The code:
private void checkBox2_CheckedChanged(object sender, EventArgs e)
{
crawlLocaly1 = new CrawlLocaly();
crawlLocaly1.StartPosition = FormStartPosition.CenterParent;
OptionsDB.Set_localOnly(checkBox2.Checked);
if (checkBox2.Checked)
{
DialogResult dr = crawlLocaly1.ShowDialog(this);
if (dr == DialogResult.Cancel)
{
crawlLocaly1.Close();
}
else if (dr == DialogResult.OK)
{
LocalyKeyWords.Add(crawlLocaly1.getText());
crawlLocaly1.Close();
}
removeExt = true;
}
else
{
removeExt = false;
}
}
This line:
OptionsDB.Set_localOnly(checkBox2.Checked);
Save the state of the checkBox2 if its checked or not. If its checked next time i will run my program i will see the V in the checkBox2 checked box. If i will uncheck the checkBox next time i run my program the box of the checkBox2 will be unchecked.
The problem is when i check the checkBox2 once close my program and run it again since the checkBox is checked now then for some reason it will make this:
DialogResult dr = crawlLocaly1.ShowDialog(this);
Wich will open and show the user a new Form.
But i dont want it to be like that.
I want that if the user checked the checkBox when the program is running the new Form will show up. But if the user is running the program from the beginning and the checkBox is checked dont show the new Form just show that the checkBox is checked !
How should i fix it ?
You need an other boolean flag checkedInThisSession which initially set to false, and just set it to true in a checkbox OnChecked handler, then you can check this state easily. Hope all is clear
private void checkBox2_CheckedChanged(object sender, EventArgs e)
{
crawlLocaly1 = new CrawlLocaly();
crawlLocaly1.StartPosition = FormStartPosition.CenterParent;
OptionsDB.Set_localOnly(checkBox2.Checked);
// UPDATED
if (checkedInThisSession && checkBox2.Checked)
{
DialogResult dr = crawlLocaly1.ShowDialog(this);
// ...
}
else
{
removeExt = false;
}
// UPDATED
checkedInThisSession = checkBox2.Checked;
}
// In constructor
checkedInThisSession = false;
checkBox2.Checked = OptionsDB.Get_localOnly();
The CheckedChanged event is fired every time the checkbox is set, also programmatically. So to solve this issue you need to ignore the first time the event is fired. So a boolean could be your solution:
private bool ignore = true;
private void checkBox2_CheckedChanged(object sender, EventArgs e){
if(ignore == false){
//your code here
}
else
ignore = false;
}

I want to programmatically generate a click on a DataGridView Row in C#

I have a DataGridView in a form and I want to programmatically click its first row. I have found code to select its rows or columns from code.
For eg.
datagridview.Columns[0].Selected = true;
datagridview.Rows[0].Selected = true;
However this code is not raising the click event on the datagridview. If any one has coded how to click a datagridview from code, please extend your kind help.
Simply call the event handler method e.g.:
datagridviewRowClickedEventHandler(new object(), new eventargs());
If you use the sender or e parameters in the event handler then you will need to work out how to pass in the correct values.
Insert the follwing code into your project where appropriate (Usually on the form which has the datagridview).
Make sure to change the name of the DataGridView from dataGridView1 to the appropriate one on your form.
private void Form1_Load(object sender, EventArgs e)
{
//call the cell click event with the first cell as the parameters.
dataGridView1_CellClick(dataGridView1, new DataGridViewCellEventArgs(0, 0));
}
private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
//put your code for handling cell click here
}
It looks like you have the first half, setting the propers rows Selected value to true. Now you can programatically call the row click handler and it should proceed as if you had clicked it within the GUI.
datagridview.Columns[0].Selected = true;
datagridview.Rows[0].Selected = true;
It makes look the row like selected but it won't change dataGridView.CurrentRow. So it could be an issue.
dataGridView.CurrentCell = dataGridView[<column>, <row>];
will change CurrentRow value too.
Hope it will help.
I assume you want to apply DataSource and select the first row? Right?
The best way to do it like this
private async void DgvAreas_RowStateChanged(object sender, DataGridViewRowStateChangedEventArgs e)
{
}
And here is the code to simulate click on row.
DgvAreas_RowStateChanged(dgvAreas, new DataGridViewRowStateChangedEventArgs(dgvAreas.Rows[0], DataGridViewElementStates.Selected));
In my case I have 3 DataGridViews so I populate the first one easly.
The second one I populate when user click the first DataGridView and in this case I use DgvStaff_RowStateChanged event.
And in this event DgvStaff_RowStateChanged I have the code to get data async and populate the third DataGridView and after I apply data source for the second DataGridView I need to get data for the first row of this view and display it in the third DataGridView. It is cascade logic.
private async void DgvStaff_RowStateChanged(object sender, DataGridViewRowStateChangedEventArgs e)
{
try
{
// For any other operation except, StateChanged, do nothing
if (e.StateChanged != DataGridViewElementStates.Selected) return;
if (sender is MetroFramework.Controls.MetroGrid)
{
if ((sender as MetroFramework.Controls.MetroGrid).SelectedRows.Count > 0)
{
dgvGeoData.DataSource = null;
dgvAreas.DataSource = null;
metroProgressSpinnerMain.Visible = true;
panelFilter.Enabled = false;
dgvAreas.RowStateChanged -= DgvAreas_RowStateChanged;
var selectedRow = (sender as MetroFramework.Controls.MetroGrid).SelectedRows[0];
var machineModelShortView = (MachineModelShortView)selectedRow.DataBoundItem;
var startTime = Convert.ToDateTime(dateTimePickerStart.Value.ToShortDateString());
var endTime = Convert.ToDateTime(metroDateTimeEnd.Value.ToShortDateString());
var areas = await UpdateAreaItems(machineModelShortView.MachineID, startTime, endTime);
if (areas.Any())
{
BeginInvoke((Action)(() =>
{
dgvAreas.DataSource = areas.OrderBy(x => x.AreaID).ThenBy(x => x.TimeStart).ToList();
dgvAreas.RowStateChanged += DgvAreas_RowStateChanged;
// !!! This is how you simulate click to the FIRST ROW dgvAreas.Rows[0]
DgvAreas_RowStateChanged(dgvAreas,
new DataGridViewRowStateChangedEventArgs(dgvAreas.Rows[0], DataGridViewElementStates.Selected));
metroProgressSpinnerMain.Visible = false;
panelFilter.Enabled = true;
}));
}
else
{
BeginInvoke((Action)(() =>
{
metroProgressSpinnerMain.Visible = false;
panelFilter.Enabled = true;
}));
}
}
}
}
catch (Exception ex)
{
logger.Error(ex);
}
}
And here
private async void DgvAreas_RowStateChanged(object sender, DataGridViewRowStateChangedEventArgs e)
{
try
{
// For any other operation except, StateChanged, do nothing
if (e.StateChanged != DataGridViewElementStates.Selected) return;
//Get GeoData
if (sender is MetroFramework.Controls.MetroGrid)
{
if ((sender as MetroFramework.Controls.MetroGrid).SelectedRows.Count > 0)
{
dgvGeoData.DataSource = null;
metroProgressSpinnerMain.Visible = true;
panelFilter.Enabled = false;
var selectedRow = (sender as MetroFramework.Controls.MetroGrid).SelectedRows[0];
var areaItem = (AreaItem)selectedRow.DataBoundItem;
var geoData = await UpdateWDataPositionItems(areaItem.MachineID, areaItem.TimeStart, areaItem.TimeEnd.Value);
if (geoData.Any())
{
BeginInvoke((Action)(() =>
{
dgvGeoData.DataSource = geoData.OrderBy(x => x.AtTime).ToList();
metroProgressSpinnerMain.Visible = false;
panelFilter.Enabled = true;
}));
}
else
{
BeginInvoke((Action)(() =>
{
metroProgressSpinnerMain.Visible = false;
panelFilter.Enabled = true;
}));
}
}
}
}
catch (Exception ex)
{
logger.Error(ex);
}
}

Categories