get code behind checkboxes in postback - c#

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.

Related

Not able to store information while postback after creating dynamic dropdown in ASP.NET

here is my code
after button 2 click event it is creating the dropdown in table rows but when I try to save by button 1 click event it just disappear. I have not find any solution regarding this. I have used find control view State etc but it's not helping.
I want to store selected values of dropdown after button_1 click event starts.
public partial class StudentClassSectionMapping : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
ClassCode.Enabled = false;
}
}
protected void Button2_Click(object sender, EventArgs e)
{
UpdateModalShowFlag.Value = "true";
Check.Value = "true";
CreateTableRows();
}
private void CreateTableRows()
{
long h = long.Parse(LinkButtonIdCarrier.Value);
List<StudentsClassSectionMapping.StudentsClassSectionMappingForm> allStudentsInClass = StudentsClassSectionMapping.GetStudentsinClass(h);
ClassMaster.ClassMasterForm classCode = Schoolclasses.GetInfo(h);
ClassCode.Text = classCode.cCode;
List<StudentsClassSectionMapping.StudentsClassSectionMappingForm> allSectionsInClass = StudentsClassSectionMapping.GetSectionsinClass(h);
foreach (StudentsClassSectionMapping.StudentsClassSectionMappingForm studentList in allStudentsInClass)
{
TableRow row = new TableRow();
TableCell cell1 = new TableCell();
TableCell cell2 = new TableCell();
TableCell cell3 = new TableCell();
DropDownList t = new DropDownList();
t.Items.Add("No Section");
foreach (StudentsClassSectionMapping.StudentsClassSectionMappingForm sectionList in allSectionsInClass)
{
t.Items.Add(sectionList.ssSection);
t.Items[t.Items.Count - 1].Value = sectionList.ssSectionID.ToString();
}
t.Attributes.Add("class", "form-control");
t.ID = studentList.ssStudentId.ToString();
cell1.Text = studentList.ssName;
cell2.Text = studentList.ssRegistrationNumber;
cell3.Controls.Add(t);
row.Cells.Add(cell1);
row.Cells.Add(cell2);
row.Cells.Add(cell3);
Table1.Rows.Add(row);
}
}
protected void Button1_Click(object sender, EventArgs e)
{
CreateTableRows();
long h = long.Parse(LinkButtonIdCarrier.Value);
List<StudentsClassSectionMapping.StudentsClassSectionMappingForm> allStudentsInClass = StudentsClassSectionMapping.GetStudentsinClass(h);
foreach (StudentsClassSectionMapping.StudentsClassSectionMappingForm studentList in allStudentsInClass)
{
DropDownList d = Table1.FindControl(studentList.ssStudentId.ToString()) as DropDownList;
if (d != null)
{
if (d.SelectedIndex != 0)
{
StudentsClassSectionMapping.StudentsClassSectionMappingForm studentSectionMapping = new StudentsClassSectionMapping.StudentsClassSectionMappingForm();
studentSectionMapping.ssClassId = h;
studentSectionMapping.ssStudentId = studentList.ssStudentId;
studentSectionMapping.ssStudentId = long.Parse(d.SelectedItem.Value);
StudentsClassSectionMapping.addSectionStudentMapping(studentSectionMapping);
}
else
{
StudentsClassSectionMapping.StudentsClassSectionMappingForm studentSectionMapping = new StudentsClassSectionMapping.StudentsClassSectionMappingForm();
studentSectionMapping.ssClassId = h;
studentSectionMapping.ssStudentId = 0;
studentSectionMapping.ssStudentId = 0;
StudentsClassSectionMapping.addSectionStudentMapping(studentSectionMapping);
}
}
}
}
It get vanished/disappear because you added it dynamically on page. If you want it back or want to reserver control which is dynamically created you need to recreate again and need to add dynamically.
Here is good example of how you can do it : How to create controls dynamically in ASP.NET and retrieve values from it

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.

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

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;

Why does findcontrol need unique id, when I have given it the row to scan

The code
public partial class Table_Traversing : System.Web.UI.Page
{
Table table1 = new Table();
Button button1 = new Button();
protected void Page_Load(object sender, EventArgs e)
{
for (int adding_rows = 0; adding_rows < 4; adding_rows++)
{
TableRow table_row1 = new TableRow();
TableCell table_cell1 = new TableCell();
TableCell table_cell2 = new TableCell();
Label The_text = new Label();
CheckBox checkmate = new CheckBox();
The_text.Text = "This is the text :-)";
checkmate.ID = "checkmate";
table_cell2.Controls.Add(checkmate);
table_cell1.Controls.Add(The_text);
table_row1.Controls.AddAt(0, table_cell1);
table_row1.Controls.AddAt(1, table_cell2);
table1.Rows.Add(table_row1);
}
button1.Text = "click me to export the value";
form1.Controls.AddAt(0, table1);
form1.Controls.AddAt(1, button1);
button1.Click += new EventHandler(button1_Click);
}
void button1_Click(object sender, EventArgs e)
{
CheckBox check_or_not = new CheckBox();
for (int i = 0; i < table1.Rows.Count; i++)
{
check_or_not = (CheckBox)table1.Rows[i].FindControl("checkmate");
Response.Write(check_or_not.Checked.ToString());
}
}
}
The error
Multiple controls with the same ID 'checkmate' were found. FindControl requires that controls have unique IDs.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.Web.HttpException: Multiple controls with the same ID 'checkmate' were found. FindControl requires that controls have unique IDs.
Just append the row number to the ID:
checkmate.ID = "checkmate" + adding_rows.ToString();
And of course, append it to your FindControl parameter as well:
check_or_not = (CheckBox)table1.Rows[i].FindControl("checkmate" + i.ToString());
You added the checkbox to the cell, not the row:
table_cell2.Controls.Add(checkmate);
Hence - one row has multiple cells with id "checkmate":
E.g
<tr id="somerow">
<td><input type="checkbox" id="checkmate"/></td>
<td><input type="checkbox" id="checkmate"/></td>
</tr>
So within the row "somerow", there are multiple checkboxes with id "checkmate".
Your code to add the checkboxes seemingly looks like you're only adding one though - so it must be something you've missed.
Try removing the FindControl code and see what actual HTML get's rendered.

Categories