I am trying to reference a non-asp check box in C# code behind. The reason the checkbox is not an asp element, is it gets auto-generated on the fly, rather than being a part of the website. So far I have the following relevant aspx:
<asp:Table ID="myTable" runat="server" Width="100%">
<asp:TableRow>
<asp:TableCell>A</asp:TableCell>
<asp:TableCell>B</asp:TableCell>
<asp:TableCell>C</asp:TableCell>
<asp:TableCell>D</asp:TableCell>
<asp:TableCell>E</asp:TableCell>
</asp:TableRow>
</asp:Table>
<asp:LinkButton runat="server" ID="TEST" CssClass="btn btn-default pull-right" OnClick="TEST_Click">
TEST <i class="m-icon-swapright m-icon-white"></i>
</asp:LinkButton>
And the C# code behind is:
public void GenerateTable()
{
int i = 0;
bool[] box = {true, false, true, false, true};
List<TableRow> tRows = new List<TableRow>();
TableRow newRow = new TableRow();
tRows.Add(newRow);
foreach (var check in box)
{
TableCell tempCell = new TableCell();
if (check)
{
tempCell.Text = "<input type=\"checkbox\" id=\"chk" + i + "\" >";
}
else
{
tempCell.Text = "<input type=\"checkbox\" id=\"chk" + i + "\" checked>";
}
tRows[0].Cells.Add(tempCell);
i++;
}
foreach (TableRow row in tRows)
{
myTable.Rows.Add(row);
}
}
public void TEST_Click(object sender, EventArgs e)
{
HtmlInputCheckBox chkbox = (HtmlInputCheckBox)FindControl("chk1");
if (chkbox != null)
{
if (!chkbox.Checked)
{
MessageBox.Show("Checked");
}
else
{
MessageBox.Show("NOT Checked");
}
}
else
MessageBox.Show("NOTHING :(");
}
chkbox is always null :(.
You'll need to change two things.
In order to find a checkbox via FindControl it must be part of the pages control collection, which means you have to add a CheckBoxcontrol.
CheckBox c = new CheckBox { ID = "chk" + i };
tempCell.Controls.Add(c);
The dynamically added CheckBox control is part of the control collection of the Table, so you'll have to search for it there instead of on the page.
CheckBox chkbox = (CheckBox)this.myTable.FindControl("chk1");
Below you find a full update of your code.
protected void Page_Load(object sender, EventArgs e)
{
GenerateTable();
}
public void GenerateTable()
{
int i = 0;
bool[] box = {true, false, true, false, true};
List<TableRow> tRows = new List<TableRow>();
TableRow newRow = new TableRow();
tRows.Add(newRow);
foreach (var check in box)
{
TableCell tempCell = new TableCell();
CheckBox c = new CheckBox { ID = "chk" + i };
c.Checked = check;
tempCell.Controls.Add(c);
tRows[0].Cells.Add(tempCell);
i++;
}
foreach (TableRow row in tRows)
{
myTable.Rows.Add(row);
}
}
public void TEST_Click(object sender, EventArgs e)
{
CheckBox chkbox = (CheckBox)this.myTable.FindControl("chk1");
if (chkbox != null)
{
if (!chkbox.Checked)
{
MessageBox.Show("Checked");
}
else
{
MessageBox.Show("NOT Checked");
}
}
else
{
MessageBox.Show("NOTHING :(");
}
}
Related
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
First time poster, long time lurker. I am having some trouble with my ASP.NET page, and I hope someone can help me resolve my issue.
Basically, I have a bunch of checkboxes in a gridview, and two buttons: a 'find' button, and a 'save' button. The 'find' can set the value of the checkbox, but if a user unchecks it, I want to capture that change when the user hits 'save'. Currently, it does not work.
Relevant ASPX:
<%# Page Language="C#" AutoEventWireup="true" EnableViewState="true" CodeBehind="FindTransactions.aspx.cs" Inherits="Basic.FindTransactions" MasterPageFile="~/Trans.Master" %>
Relevant Code Behind here:
Page:
public partial class FindTransactions : System.Web.UI.Page
{
GridView _gridview = new GridView() { ID = "_gridView" };
DataTable _datatable = new DataTable();
Int32 _buyerID = new Int32();
protected void Page_Load(object sender, EventArgs e)
{
}
"Find" button:
protected void Find_Click(object sender, EventArgs e)
{
//truncated
_datatable.Rows.Add(
//filled with other data from a custom object.
);
ViewState["_datatable"] = _datatable;
ViewState["_buyerID"] = _buyerID;
BuildGridView((DataTable)ViewState["_datatable"],(Int32)ViewState["buyerID"]);
}
BuildGridView function:
protected void BuildGridView(DataTable d, Int32 b)
{
_gridview.DataKeyNames = new String[] {"Transaction ID"};
_gridview.AutoGenerateColumns = false;
_gridview.RowDataBound += new GridViewRowEventHandler(OnRowDataBound);
for(Int32 i = 0; i < d.Columns.Count; i++)
{
Boundfield boundfield = new BoundField();
boundfield.DataField = d.Columns[i].ColumnName.ToString();
boundfield.HeaderText = d.Columns[i].ColumnName.ToString();
_gridview.Columns.Add(boundfield);
}
_gridview.DataSource = d;
_gridview.DataBind();
//truncated
Panel1.Controls.Add(_gridview);
}
Row Bound Event handler:
protected void OnRowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
String controlID = "checkBox";
CheckBox c = new CheckBox() { ID = controlID};
c.Enabled = true;
Boolean success;
Boolean v;
success = Boolean.TryParse(e.Row.Cells[8].Text, out v);
e.Row.Cells[8].Controls.Add(c);
if (success)
{
c.Checked = v;
if (c.Checked)
{
//Will uncomment once other things work
//e.Row.Visible = false;
}
}
else
{
c.Checked = false;
}
}
}
All of that works. Here is where it starts to break down:
"Save" button:
protected void Save_Click(object sender, EventArgs e)
{
//Both for troubleshooting and both return 0. (Expected for datatable)
Label1.Text = _gridview.Rows.Count.ToString();
Label2.Text = _datatable.Rows.Count.ToString();
/*truncated
*/
if (grid.Rows.Count == 0)
{
BuildGridView((DataTable)ViewState["infoTable"], (Int32)ViewState["guestID"]);
}
foreach (GridViewRow r in grid.Rows)
{
if (r.RowType == DataControlRowType.DataRow)
{
CheckBox cb = (CheckBox)r.FindControl("checkBox");
if (cb != null && cb.Checked)
{
//This never seems to modify the label.
//Will put code to modify database here.
Label2.Text += "Hi " + r.RowIndex.ToString();
}
}
}
}
After I hit the save button, PostBack occurs and GridView is empty (Rows.Count is 0). ViewState appears to be lost before I get a chance to loop through the GridView rows to determine the checkbox values.
At the end of it all, I just want to capture the status of those checkboxes, changed by user interaction or not, by hitting the 'Save' button.
I found some other articles, but a lot of them haven't worked when I tried implementing the various fixes.
This one seems to be the closest that describes my issue, and the code is structured similarly, but I don't quite understand how to implement the fix: GridView doesn't remember state between postbacks
[New simplified code to illustrate problem:]
namespace GridViewIssue
{
public partial class GridViewNoMaster : System.Web.UI.Page
{
GridView _gridView = new GridView() { ID = "_gridView" };
DataTable _dataTable = new DataTable();
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Find_Click(object sender, EventArgs e)
{
BuildDataTable();
List<String> list = new List<String>();
list.Add("1");
list.Add("User");
list.Add("10/12/2014");
foreach (String s in list)
{
_dataTable.Rows.Add(
list[0],
list[1],
list[2]
);
}
BuildGridView();
//Feedback.Text = _gridView.Rows.Count.ToString();
}
protected void Save_Click(object sender, EventArgs e)
{
Feedback.Text = "Save Clicked, PostBack: " + IsPostBack + ", GridView Row Count: " + _gridView.Rows.Count + ", GridView ViewState: " + _gridView.EnableViewState;
foreach (GridViewRow r in _gridView.Rows)
{
if(r.RowType == DataControlRowType.DataRow)
{
Feedback.Text = "In DataRow type" + _gridView.Rows.Count;
}
}
}
protected void BuildDataTable()
{
_dataTable.Columns.Add("Transaction ID", typeof(String));
_dataTable.Columns.Add("Name", typeof(String));
_dataTable.Columns.Add("Date", typeof(String));
}
protected void BuildGridView()
{
for (Int32 i = 0; i < _dataTable.Columns.Count; i++)
{
BoundField b = new BoundField();
b.DataField = _dataTable.Columns[i].ColumnName.ToString();
b.HeaderText = _dataTable.Columns[i].ColumnName.ToString();
_gridView.Columns.Add(b);
}
_gridView.DataKeyNames = new String[] { "Transaction ID" };
_gridView.AutoGenerateColumns = false;
_gridView.DataSource = _dataTable;
_gridView.DataBind();
Panel1.Controls.Add(_gridView);
}
}
}
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.
I have populated my checkboxlist on the fly via callback like this:
<dx:ASPxComboBox ID="ASPxComboBox_Prot" runat="server" DataSourceID="SqlDataSource_Prot"
TextField="LIBELLE" ValueField="NO_PROT" ValueType="System.Int32">
<ClientSideEvents SelectedIndexChanged="function(s, e) { cbp_ProtOrdos.PerformCallback(s.GetValue());}" />
</dx:ASPxComboBox>
</td>
</tr>
</table>
<dx:ASPxCallbackPanel ID="ASPxCallbackPanel_ProtOrdo" runat="server"
ClientInstanceName="cbp_ProtOrdos" OnCallback="cbp_ProtOrdo_Callback">
<PanelCollection>
<dx:PanelContent>
<dx:ASPxCheckBoxList ID="CheckBoxList_Ordo" runat="server" ClientInstanceName="CheckBoxList_Ordo" ValueType="System.Int32" TextField="LIBELLE" ValueField="NO_ORDO">
</dx:ASPxCheckBoxList>
<dx:ASPxButton ID="ASPxButton_ProtOrdoGen" runat="server"
Text="Générer ordonnance & Planifier pour infirmier"
OnClick="ASPxButton_ProtOrdoGen_Click"
EnableDefaultAppearance="false" BackColor="Yellow" CssClass="bt" Theme="BlackGlass" ForeColor="Black">
</dx:ASPxButton>
</dx:PanelContent>
</PanelCollection>
</dx:ASPxCallbackPanel>
And on server side code:
protected void cbp_ProtOrdo_Callback(object sender, DevExpress.Web.ASPxClasses.CallbackEventArgsBase e)
{
var panel = sender as ASPxCallbackPanel;
var cblist = panel.FindControl("CheckBoxList_Ordo") as ASPxCheckBoxList;
cblist.DataSource = Outils.Get_ProtOrdo(ASPxComboBox_Prot.Value.ToString());
cblist.DataBind();
}
It works fine, but now I want to get the value that had been checked by the user. So I add the button to do that.
protected void ASPxButton_ProtOrdoGen_Click(object sender, EventArgs e)
{
//TabPage oPage = ASPxPageControl_DosSoin.TabPages.FindByName("Surveillance");
//ASPxPanel oPanel = (ASPxPanel)oPage.FindControl("ASPxPanel_ListSurveil");
//ASPxRoundPanel oRoundPnl = (ASPxRoundPanel)oPanel.FindControl("ASPxRoundPanel_ProtOrdo");
//ASPxCallbackPanel ocbpPanel = (ASPxCallbackPanel)oRoundPnl.FindControl("ASPxCallbackPanel_ProtOrdo");
//ASPxCheckBoxList cblist = (ASPxCheckBoxList)ocbpPanel.FindControl("CheckBoxList_Ordo") as ASPxCheckBoxList;
List<string> selectItems_Ordo = new List<string>();
foreach (var oItem in CheckBoxList_Ordo.Items)
{
ListEditItem oNewChk = (ListEditItem)oItem;
if (oNewChk.Selected)
{
selectItems_Ordo.Add( oNewChk.Value.ToString());
}
}
foreach (var oItem in selectItems_Ordo)
{
if (DossierDuSoins.check_doublon_ordo(oItem.ToString(), Soin_Id) == 0)
DossierDuSoins.RamenerVal(DossierDuSoins.GetLibOrdo(oItem.ToString()), Soin_Id, oItem.ToString());
}
string TempId = "";
if (selectItems_Ordo.Count == 0)
{
lbl_err.Text = "Pas de médicament de sélectionné";
}
else
{
foreach (string selectItemId in selectItems_Ordo)
{
if (TempId != "")
TempId += ",";
TempId += selectItemId.ToString();
}
string AdrUrl = "Print_Ordo.aspx?SoinId=" + Soin_Id + "&SelId=" + TempId;
ClientScript.RegisterStartupScript(this.GetType(), "newWindow", String.Format("<script>window.open('{0}');</script>", AdrUrl));
}
}
The problem is that I can not get my checked value. Is that because the postback destroys all checkboxlists that I had constructed on the fly ?
Try this instead of using vars for selecting your checkbox list
foreach (ListItem yourItem in YourCheckBoxList.Items)
{
if (item.Selected)
{
// If the item is selected, Add to your list/ save to DB
}
else
{
// If item is not selected, do something else.
}
}
i'm having trouble with a Button . The Click event is not working, i'm adding this button to a cell on a table. The rows for the table are filled from a List. It's a simple project for college. I'm already using this code on a previous page and it works.
Here's my code:
aspx:
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
<!-- Nombre del Cliente -->
<asp:Label ID="lblNombreCliente" CssClass="lbl negrita fs30" runat="server" Text="Cliente: " />
<!-- Listado de Proyectos-->
<asp:Table ID="tblProyectos" CssClass="tbl" runat="server">
<asp:TableRow>
<asp:TableHeaderCell CssClass="th w10">Cod</asp:TableHeaderCell>
<asp:TableHeaderCell CssClass="th">Nombre</asp:TableHeaderCell>
<asp:TableHeaderCell CssClass="th w10">Horas</asp:TableHeaderCell>
<asp:TableHeaderCell CssClass="th w20">Encargado</asp:TableHeaderCell>
<asp:TableHeaderCell CssClass="th">Ver</asp:TableHeaderCell>
</asp:TableRow>
</asp:Table>
CS:
protected void Page_Load(object sender, EventArgs e)
{
int codCliente = 0;
if(!IsPostBack)
{
//Usuario Conectado
string nombre = Request.Params["usuario"];
if (nombre != null)
{
this.Master.datosUsuario = String.Format(nombre);
}
//Codigo Cliente
codCliente = int.Parse(Request.Params["codCliente"]);
if (codCliente != 0)
{
foreach (Cliente objCliente in listaClientes)
{
if (objCliente.Cod_cliente == codCliente)
{
lblNombreCliente.Text = objCliente.Nombre;
}
}
}
}//fin isPostBack
//Se agregan proyectos a la tbl
int i = 1;
foreach (Proyecto item in listaProyectos)
{
//Se rellenan las celdas
if (item.Cod_cliente == codCliente)
{
TableRow fila = new TableRow();
TableCell cod = new TableCell();
TableCell nombre_proyecto = new TableCell();
TableCell horas = new TableCell();
TableCell encargado = new TableCell();
TableCell btnsProyecto = new TableCell();
string nombre_encargado = string.Empty;
foreach (Usuario usu in listaUsuarios)
{
if(usu.Cod_usuario == item.Cod_encargado){
nombre_encargado = usu.Nombre;
break;
}
}
Button btnIngreso = new Button();
btnIngreso.CssClass = "btn";
btnIngreso.Text = "Ingresar";
btnIngreso.ID = "btnIngresar_" + i;
btnIngreso.Click += new EventHandler(this.btnIngresar_Click);
btnsProyecto.Controls.Add(btnIngreso);
cod.Text = item.Cod_proyecto.ToString();
nombre_proyecto.Text = item.Nombre_proyecto;
horas.Text = item.Horas.ToString();
encargado.Text = nombre_encargado;
//Se agregan las celdas
fila.Cells.Add(cod);
fila.Cells.Add(nombre_proyecto);
fila.Cells.Add(horas);
fila.Cells.Add(encargado);
fila.Cells.Add(btnsProyecto);
tblProyectos.Rows.Add(fila);
i++;
}
}//fin foreach tbl
}//fin page_load
protected void btnIngresar_Click(Object sender, EventArgs e)
{
Button btn = (Button)sender;
int fila = int.Parse(btn.ID.Substring(btn.ID.Length - 1));
int codProyecto = int.Parse(tblProyectos.Rows[fila].Cells[0].Text);
string url = String.Format("{0}?codProyecto={1}&usuario={2}"
, "IngresoMantencion.aspx"
, codProyecto, this.objUsuario.Nombre);
Response.Redirect(url);
}
I'm from Chile, that's why my code has spanish words. I hope you can help me.
Thanks!
Your button is called Button btnIngreso = new Button(); but you call protected void btnIngresar_Click(Object sender, EventArgs e)
Rename the handler to protected void btnIngreso_Click(Object sender, EventArgs e) and see if it works.
Hope that helps,
Chris