Deleteing a panel after checkbox checked - c#

I have a code that generates multiple panels, each including some labels and comboboxes. One of the controls included in each panel is a checkbox, what I need to do is, that when user checks the checkbox, the whole panel where the checkbox was will be deleted.
Inside a foreach loop that generates the panels, the panel itself can be reached with name "Strip". Outside this loop, if I would transfer all necessary parameters(or arguments, not sure about the terminology here), it would be called after one of its labels "callsign", so when I need to get its name out into a method, I set as a parameter "callsign.Text".
Now, here is my Checbox generating code:
CheckBox check = new CheckBox();
check.Location = new Point(270, 10);
check.Name = "check:" + callsign.Text;
check.CheckedChanged += new System.EventHandler(CheckCheckedChanged(callsign.Text));
Strip.Controls.Add(check);
and here is definition of method CheckCheckedChanged:
public void CheckCheckedChanged(string callsign, object sender, EventArgs e)
{
}
... First of all, I get en error at line check.CheckedChanged += new System.EventHandler(CheckCheckedChanged(callsign.Text));
It says, that "No overload for method CheckCheckedChanged takes 1 arguments". I dont know whats wrong, so thats my first question. The second is - I cant figure out how to write the method to delete the one specific panel named after the callsign.Text, if I would write just "callsign dispose" then I guess it wouldnt work.
Thanks in advance

The first thing you need to do is remove the string callsign parameter from your event handler. That is what's causing the compiler error. So your method signature will look like this:
public void CheckCheckedChanged(object sender, EventArgs e)
Secondly, you need to change how the event is attached to event handler:
check.CheckedChanged += new System.EventHandler(CheckCheckedChanged(callsign.Text));
will become:
check.CheckedChanged += new System.EventHandler(CheckCheckedChanged);
Next, you want to put code into the event handler to get the state of the checkbox and set the visibility of the panel accordingly. You will replace the panel with the name of your panel.
public void CheckCheckedChanged(object sender, EventArgs e)
{
CheckBox checkbox = sender as CheckBox;
if (checkbox != null)
{
((Panel)checkbox.Parent).Visible = !checkbox.Checked; // replace this with your panel
}
}

Related

c# format textboxes to currency when they lose focus

I have several lists of text boxes on a form each representing a column of a database. I want to update the form each time the user exits one of the boxes for price. the name of this list is priceBox[]. I am aware of the lostFocus event but I cant seem to figure a way to get it to work for a collection and this list can grow so I cant have a fixed number. I dont have any code for this yet. if it helps the text box controls are contained in a panel named panel1.
I have tried searching and cant find anything on this. only for singular instances, like updating 1 text box.
sorry if this is a duplicate but I did try to search. also I am new to c#.
thanks.
One approach is adding a ControlAdded handler to the panel, so every time a new textbox is added, it automatically adds LostFocus handler for it. Step-by-step below:
For your panel you bind a handler ControlAdded event, which would be something like:
private void Panel1_ControlAdded(object sender, ControlEventArgs e)
{
var tb = e.Control as TextBox;
if (tb != null)
{
tb.LostFocus += new EventHandler(TextBox_LostFocus);
}
}
Then in TextBox_LostFocus you can add whatever logic you want
void TextBox_LostFocus(object sender, EventArgs e)
{
var tb = sender as TextBox;
if (tb != null)
{
// modify tb.Text here, possibly like this...
tb.Text = String.Format("{0:C}", Decimal.Parse(tb.Text));
}
}
To update all existing controls (not tested)
foreach (TextBox in panel1.Controls)
{
tb.LostFocus += new EventHandler(TextBox_LostFocus);
}

Placing a TextBox on top of a header column in a DataGridView

I have the following function that responds to the ColumnHeaderMouseDoubleClick event in a DataGridView:
void grid_ColumnHeaderMouseDoubleClick(object sender, DataGridViewCellMouseEventArgs e) {
TextBox t = new TextBox();
//make the new textbox the same size as the header to cover it up until text is entered
t.Width = ((DataGridView)sender).CurrentCell.ContentBounds.Width;
t.Height = ((DataGridView)sender).CurrentCell.ContentBounds.Height;
t.Dock = DockStyle.Fill;
t.Visible = true;
t.BringToFront();
t.Text = "TEST";
Controls.Add(t);
}
All of this code is happening inside of a class that extends Panel and had a DataGridView added to the controls of the panel. When I double click on a header and put a breakpoint on this handler the handler is called, but I don't see the textbox anywhere. Does anybody know what I'm doing wrong?
I would start by making the textbox a class field (declare it outside the event trigger so it doesn't go out of scope by the end of it). Might have to set the coordinates for the textBox as well :). Don't have VS on this machine to try this out but I hope this will help.

Parameterised Drill down with Gridview

I'm trying to get a Gridview "select" link to drill down to a specific page for the selected row in ASP.NET with C#. This gridview is generated dynamically in the page_load, and is databound from a fairly simple SQL select query. Each row has a unique id, and I would like this to be passed as a parameter in the url when the select button is clicked for that row. So, when you click the "select" button on the row with an id value of 9 (note - not the id as defined by the gridview, but the one from the SQL query) you are redirected to an address such as moreDetail.aspx?id=9.
However, when trying to pass the id into the event handler I've hit issues... GridView.SelectedIndexChanging takes the usual (object sender, EventArgs e) as parameters and nothing else, and since the Gridview is created at Page_Load the EventArgs class is useless. I can't seem to find any way to pass the id that I have retrieved earlier into the event handler.
After lots of searching,I tried creating a class that extends EventArgs (obviously with my extra parameter added in), but it seems using any parameters other than (object sender, EventArgs e) just won't work. I could theoretically redo the SQL query within the event handler, but that seems to me a terrible way to achieve what I'm looking for, so I'm hoping someone will be able to see what I've got wrong here, because I'm sure I'm missing something obvious.
Some code - grid.SelectedRow.Cells[0] will contain the parameter I want to pass:
In Page_Load:
GridView grid = new GridView();
grid.DataSource = source;
CommandField selectField = new CommandField();
selectField.ShowSelectButton = true;
selectField.SelectText = "View Jobs";
grid.Columns.Add(selectField);
grid.SelectedIndexChanging += grid_SelectedIndexChanging;
grid.DataBind();
content.Controls.Add(grid);
And the Event Handler:
protected void grid_SelectedIndexChanging(object sender, EventArgs e)
{
Response.Redirect("ViewCustomer.aspx?id=" + grid.SelectedRow.Cells[0]);
}
Obviously this doesn't work because the scope of grid doesn't extend to the handler...but how can I get access to that data?
You need to cast sender to GridView to reference your calling GridView:
protected void grid_SelectedIndexChanging(object sender, EventArgs e)
{
GridView grid = (GridView)sender;
Response.Redirect("ViewCustomer.aspx?id=" + grid.SelectedRow.Cells[0]);
}

Dynamic Placeholder Control and attaching an Event

I have been getting some massive head aches working on a very dynamic app.
I am using a dynamic placeholder control from:
http://www.denisbauer.com/ASPNETControls/DynamicControlsPlaceholder.aspx
This saves me a lot of hassle when trying to re-create dynamically created controls after a postback.
Has anyone else had any issues with attaching a event handler to checkbox control?
Here is my code for the dynamically created checkbox.
// Now I create my checkbox
chkDynamic = new CheckBox();
string chk = "chk";
// Add it to our dynamic control
chkDynamic.CheckedChanged += new EventHandler(chkDynamic_CheckedChanged);
chkDynamic.ID = chk;
DynamicControlsPlaceholder1.Controls.Add(chkDynamic);
chkDynamic.Text = "hey";
This works, but its like the event is not getting attached!
Here is my event handler!
protected void chkDynamic_CheckedChanged(object sender, EventArgs e)
{
if (((CheckBox)sender).Checked)
Response.Write("you checked the checkbox :" + this.chkDynamic.ID);
else
Response.Write("checkbox is not checked");
}
Now if I was to use a regular placeholder or a panel this works great.
Ex. Change this line:
DynamicControlsPlaceholder1.Controls.Add(chkDynamic);
to
Panel1.Controls.Add(chkDynamic);
And it works perfect.
Could someone please tell me, is this an issue with this control, or my coding?
There are no errors, the only thing that is happening that is unexpected is my event is not firing when I'm using the DynamicControlsPlaceholder.
Creating a delegate (anonymous method) did the job for me.
// Now I create my checkbox
chkDynamic = new CheckBox();
string chk = "chk";
// Add it to our dynamic control
chkDynamic.CheckedChanged += delegate (System.Object o, System.EventArgs e)
{
if (((CheckBox)sender).Checked)
Response.Write("you checked the checkbox :" + this.chkDynamic.ID);
else
Response.Write("checkbox is not checked");
};
chkDynamic.ID = chk;
DynamicControlsPlaceholder1.Controls.Add(chkDynamic);
chkDynamic.Text = "hey";
this will cause the code written in delegate to execute whenever dynamic control hits the action "CheckedChanged"
If you are adding dynamic controls, you MUST create/recreate the controls no later than OnInit(). This is the point in the .NET page lifecycle where the viewstate and events are restored. If it is solely for the purpose of adding dynamic controls that you are using the dynamic placeholder control, then simply putting the control creation/recreation in OnInit() will solve your problem. Give it a try and let me know your results.
Ok, so this works with one dynamically created control. But not with multiple...

How to check whether Check box inside data grid view is checked or not

How can i check for the bool condition of a check box which is in datagridview. I would like to have true if checked and false if it was unchecked. Can any one help me.
Is it possible to handle this in dataGridView_CellContentClick
This is addressed a little bit on the MSDN pages for the DataGridView here and here.
In particular they say:
For clicks in a DataGridViewCheckBoxCell, this event occurs before the
check box changes value, so if you do not want to calculate the
expected value based on the current value, you will typically handle
the DataGridView.CellValueChanged event instead. Because that event
occurs only when the user-specified value is committed, which
typically occurs when focus leaves the cell, you must also handle the
DataGridView.CurrentCellDirtyStateChanged event. In that handler, if
the current cell is a check box cell, call the DataGridView.CommitEdit
method and pass in the Commit value.
So they recommend against using the CellClick type events (since they never push the value until you leave the cell) but instead use CurrentCellDirtyStateChanged and the CommitEdit method.
So you end up with:
dataGridView1.CurrentCellDirtyStateChanged += new EventHandler(dataGridView1_CurrentCellDirtyStateChanged);
dataGridView1.CellValueChanged += new DataGridViewCellEventHandler(dataGridView1_CellValueChanged);
void dataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
if (dataGridView1.Columns[e.ColumnIndex].Name == "CB")
{
MessageBox.Show(dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString());
}
}
void dataGridView1_CurrentCellDirtyStateChanged(object sender, EventArgs e)
{
dataGridView1.CommitEdit(DataGridViewDataErrorContexts.Commit);
}
And as for getting the checked value - this is just the Value property of the DataGridViewCheckBoxCell.
So if you go:
dataGridView1.Rows[rowindex].Cells[cellindex].Value
you get a boolean value which corresponds to the checkbox (after the change has been committed).
if the checkbox is defined in the designer it would be as simple asreferring to the checkbox´s name and checking its "checked" property for true/false.
But i suspect you are adding the checkbox to the datagrid by code?
in this case youll have to save a reference to the checkbox somwhere.
If i where you i would add all the checkboxes that i add to the datagrid to a list or if you want to refer to them by name i would add them to a dictionary.
You could also bind an event to the checkbox Checked_Changed event by selecting it and clicking the little bolt icon in the properties panel and finding the checkedChanged-event and doubleclicking it.
in the event-code you can obtain the checkbox clicked by typing:
CheckBox mycheckbox = sender as CheckBox;
and then refering to mycheckbox.checked to get a bool for if its checked or not.
You can try to get this in this fashion, say in case you are looping the grid the based on the index you can find the checked state.
bool IsChecked = Convert.ToBoolean((dataGridView1[ColumnIndex, RowIndex] as DataGridViewCheckBoxCell).FormattedValue))
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
var checkcell = new DataGridViewCheckBoxCell();
checkcell.FalseValue = false;
checkcell.TrueValue = true;
checkcell.Value = false;
dataGridView1[0, 0] = checkcell; //Adding the checkbox
if (((bool)((DataGridViewCheckBoxCell)dataGridView1[0, 0]).Value) == true)
{
//Stuff to do if the checkbox is checked
}
}
It works 100 %.
private void grd_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
grd.CommitEdit(DataGridViewDataErrorContexts.Commit);
bool Result = Convert.ToBoolean((grd[e.ColumnIndex, e.RowIndex] as DataGridViewCheckBoxCell).Value);
}

Categories

Resources