Checkbox Checked Event for multiple dynamic Checkboxes - c#

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
}
}

Related

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)
{
...
}

get code behind checkboxes in postback

I want to add some checkboxes at the beginning of every row in a table in the page_load: (I add them in a asp:placeholder)
protected void Page_Load(object sender, EventArgs e)
{
Table dtTable = new Table();
TableHeaderRow dtHeaderRow = new TableHeaderRow();
TableHeaderCell dtHeaderCheckbox = new TableHeaderCell();
dtHeaderCheckbox.Controls.Add(dtHeaderCkBox);
dtHeaderRow.Cells.Add(dtHeaderCheckbox);
foreach (DataColumn col in _ds.Tables[0].Columns)
{
TableHeaderCell dtHeaderCell = new TableHeaderCell();
dtHeaderCell.Text += col.ColumnName;
dtHeaderRow.Cells.Add(dtHeaderCell);
}
dtTable.Rows.Add(dtHeaderRow);
TableRow row;
for (int i = 0; i < _ds.Tables[0].Rows.Count; i++)
{
row = new TableRow();
TableCell dtCell = new TableCell();
CheckBox ckBox = new CheckBox();
ckBox.ID = "chkBox_" + _ds.Tables[0].Rows[i]["IDENTIFIER"].ToString();
ckBox.AutoPostBack = false;
ckBox.EnableViewState = false;
dtCell.Controls.Add(ckBox);
row.Cells.Add(dtCell);
for (int j = 0; j < _ds.Tables[0].Columns.Count; j++)
{
TableCell cell = new TableCell();
cell.Text = _ds.Tables[0].Rows[i][j].ToString();
row.Cells.Add(cell);
}
dtTable.Rows.Add(row);
}
phUnconfirmedDiv.Controls.Add(dtTable);
}
The problem is now, when the user press a submit button(and postback), I don't have access to my checkboxes:
protected void btnAccept_OnClick(object sender, EventArgs e)
{
List<CheckBox> chkList = new List<CheckBox>();
foreach (Control ctl in form1.Controls)
{
if (ctl is CheckBox)
{
if (ctl.ID.IndexOf("chkBox_") == 0)
{
chkList.Add((CheckBox)ctl);
}
}
}
ScriptManager.RegisterStartupScript(this, GetType(), "event", "alert('" + chkList.Count + "');", true);
}
Dynamically generated controls lost their state once they are rendered on view. And for you, to access them again in your code-behind, when your postbacks, you will have to re-create them and after that you will be able to manipulate them.
As far as getting the checked values of the checkboxes is concerned, you could try something like this. This might not be exact, should give an idea though.
This would be your check-box :
<input type="checkbox" id="yourId" name="selectedIds" value="someValue"/>
In your codebehind :
value = Request.Form["selectedIds"];
Hope this helps.
I now managed to solve this problem. Thanks all for your tips!
All checkboxes that are checked are sent through the postback. So the "easiest" way is to search for all parameters, sent in postback, that are beginning like "chkBox_" and then save them in a list/array. So I know which data should be updated in my database:
protected void btnAccept_OnClick(object sender, EventArgs e)
{
List<String> chkList = new List<String>();
// All checked checkboxes are sent via the postback. Save this parameters in a list:
foreach (string s in Request.Params.Keys)
{
if (s.ToString().IndexOf("chkBox_") == 0)
{
chkList.Add(s.ToString());
}
}
Is autopostback set to true on the user interface controls for the button? ei:
<telerik:RadButton runat="server" ID="rBtnRelease" Text="Release" Width="100px" OnClick="rBtnRelease_Click" AutoPostBack="False"/>
That's usually the common mistake when one tries to get data back and forth between the client and the server side.

Accessing dynamically generated dropdownlist in Gridview_RowUpdating event

I am using Gridview with AutoGenerateColumns="True", so gridview columns are generated dynamically. Now in case of edit, I am adding dropdownlist dynamically for one of the field in the gridview. Please see following code:
protected void grdViewConfig_RowEditing(object sender, GridViewEditEventArgs e)
{
grdViewConfig.EditIndex = e.NewEditIndex;
BindGridView();
clientBAL = new TMIWsBALClient();
var lstAppIds = clientBAL.GetDistinctApplicationIds();
GridViewRow grdRow = grdViewConfig.Rows[e.NewEditIndex];
for (int i = 0; i < grdRow.Cells.Count; i++)
{
if (grdRow.Cells[i].GetType().Equals(typeof(DataControlFieldCell)))
{
DataControlFieldCell dcField = (DataControlFieldCell )grdRow.Cells[i];
if (dcField.ContainingField.HeaderText.ToLower().Equals("applicationid"))
{
DropDownList drpDwnAppIds = new DropDownList();
drpDwnAppIds.ID = "drpDwnAppIds";
drpDwnAppIds.DataSource = lstAppIds;
drpDwnAppIds.DataBind();
var tb = dcField.GetAllControlsOfType<TextBox>(); ;// grdRow.Cells[i].GetAllControlsOfType<TextBox>();
TextBox firstTb = (TextBox)tb.First();
foreach (ListItem lstItem in drpDwnAppIds.Items)
{
if (firstTb.Text.Equals(lstItem.Text, StringComparison.CurrentCultureIgnoreCase))
{
lstItem.Selected = true;
}
}
dcField.Controls.Remove(firstTb);
dcField.Controls.Add(drpDwnAppIds);
}
}
}
}
Now in Gridview_RowUpdating event, I am trying to fetch the dropdownlist in similar way, but I am unable to get it. GetAllControlsOfType() is an extension method, which will return all the child controls under selected parent. In this case, parent is gridview cell and child control is dropdownlist. But it is returning null.
protected void grdViewConfig_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
strTableName = txtTable.Text.Trim();
string strAppId;
GridViewRow grdRow = grdViewConfig.Rows[grdViewConfig.EditIndex];
for (int i = 0; i < grdRow.Cells.Count; i++)
{
if (grdRow.Cells[i].GetType().Equals(typeof(DataControlFieldCell)))
{
DataControlFieldCell dcField = (DataControlFieldCell)grdRow.Cells[i];
if (dcField.ContainingField.HeaderText.ToLower().Equals("applicationid"))
{
var drpDwn = dcField.GetAllControlsOfType<DropDownList>();
DropDownList drpDwnAppIds = (DropDownList)drpDwn.First();
strAppId = drpDwnAppIds.SelectedValue;
}
}
}
}
What am I missing? Please help. Also let me know if more information is needed.
Thank you in advance.
Dynamically generated controls need to be recreated on every postback. In your case the DropDownList controls you created no longer exist when you hit the grdViewConfig_RowUpdating handler.
Generally in this sort of case you would set AutoGenerateColumns to false and manually define your columns which would allow you to define a TemplateField which contains an ItemTemplate for read only mode and an EditItemTemplate for edit mode which could then contain your DropDownList.

Checked_Change Event of programatically generated Checkbox inside GridView Row

I have a GridView which holds user data. When the Page_Load Method is called, I get data using a DataTable and then bind it to the GridView. At the end of each row, I have added a CheckBox. This CB is used as a pointer for which entity the user wants to edit.
My problem is the Check_Changed Event of the CheckBoxes. I do not know how to add a handler if the control is generated programmatically. I also need the index of the row (a field value is also possible, but the column header and the column itself are hidden).
foreach (GridViewRow gvr in grdMitgliedsliste.Rows)
{
//add checkbox for every row
TableCell cell = new TableCell();
CheckBox box = new CheckBox();
cell.Controls.Add(box);
gvr.Cells.Add(cell);
//Hide columns for userid, status, etc.
gvr.Cells[0].Visible = false;
gvr.Cells[3].Visible = false;
gvr.Cells[4].Visible = false;
gvr.Cells[5].Visible = false;
gvr.Cells[8].Visible = false;
gvr.Cells[9].Visible = false;
}
I have already tried implementing the handler from here, but it gives me no index argument so the program cannot determine in which row the checkbox was checked.
protected void Page_Load(object sender, EventArgs e)
{
List<string> names = new List<string>();
names.Add("Jhonatas");
this.GridView1.DataSource = names;
this.GridView1.DataBind();
foreach (GridViewRow gvr in GridView1.Rows)
{
//add checkbox for every row
TableCell cell = new TableCell();
CheckBox box = new CheckBox();
box.AutoPostBack = true;
box.ID = gvr.Cells[0].Text;
box.CheckedChanged += new EventHandler(box_CheckedChanged);
cell.Controls.Add(box);
gvr.Cells.Add(cell);
}
}
void box_CheckedChanged(object sender, EventArgs e)
{
string test = "ok";
}
TableCell cell = new TableCell();
CheckBox box = new CheckBox();
box.Check += new EventHandler(Checked_Changed);
cell.Controls.Add(box);
gvr.Cells.Add(cell);
sorry, im allready about to drive home so its just an fast answer.
mabye you have to correct the event after box."event" ...
You should go this way:
first of all when you are generating the checkbox
CheckBox box = new CheckBox();
box.AutoPostBack=true;
provide an id to the checkbox as
box.ID=Convert.toString(Session["Count"]);
do initialize the "Count" when the page loads in the session.
also increment the "Count" everytime you add a new checkbox.
secondly, define the event handler for your dynamic check box like this:
box.CheckedChange += MyHandler;
and define the MyHandler
protected void MyHandler(object sender, EventArgs e)
{
//Do some stuff
}
now you may get the id for the checkbox from which the event has been fired inside the MyHandler, which will actually be the row number.
CheckBox cb = (CheckBox)sender;
string id = cb.ID;

RowCommand not getting fired on Dynamically created GridView

I am creating a gridview dynamically with a ButtonField and several BoundFields. ButtonField button type is LinkButton. If i run it the buttonclick triggers a post back but rowCommand is not triggered. It is not triggered even if i use AutogenerateSelectButton. The event is dyanamically bound. Code As follows:
protected void B_Search_Click(object sender, EventArgs e) //Search buttonclick that creates and displays the gridview
{
gd = getGridView(); //defines the gridview with columns and buttonfield
gd.DataSource = executeAdvanceSearch(); //retrieves data from DB as Dataset
gd.DataBind();
gd.RowCommand += new GridViewCommandEventHandler(gdView_RowCommand); //Rowcommand event binding
PlaceHolder1.Controls.Add(gd);
}
protected void gdView_RowCommand(object sender, GridViewCommandEventArgs e) //not getting triggered on postback
{
int index = Convert.ToInt32(e.CommandArgument);
GridView gdView = (GridView)sender;
if (e.CommandName == "IDClick")
{
//Do something
}
}
private GridView getGridView()
{
GridView gdView = new GridView();
gdView.AutoGenerateColumns = false;
gdView.AutoGenerateSelectButton = true;
string name;
string[] field = ZGP.BLL.Search.getResultFormat(Convert.ToInt32(DDL_ResultView.SelectedValue), out name); //Ignore. This jst gets columnNames
if (field.Count() != 0)
{
gdView.Columns.Add(getSelectButton()); //Adds linkbutton
foreach (string cName in field) //ignore. This adds columns.
if (!String.IsNullOrEmpty(cName))
{
gdView.Columns.Add(GV_DataColumn.getGridViewColumn((DataColumnName)Enum.Parse(typeof(DataColumnName), cName))); //Ignore. adds columns
}
}
return gdView;
}
private ButtonField getSelectButton()
{
ButtonField _bf = new ButtonField();
_bf.ButtonType = ButtonType.Link;
_bf.HeaderText = "ID";
_bf.DataTextField = "ID";
_bf.CommandName = "IDClick";
return _bf;
}
Thanks for the help.
if (e.CommandName=="CommandName")
{
int index = Convert.ToInt32(e.CommandArgument);
GridViewRow row = GridView1.Rows[index];
string boundFieldText= row.Cells[0].Text;
}
You'll need to create the grid view on each postback.

Categories