Cannot get the value on server side after callback - c#

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

Related

Reference non asp checkbox in code behind

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 :(");
}
}

stop postback on treeview node click

I followed this tutorial to allow a user to select a folder from their machine:
http://www.codeproject.com/Articles/21895/Directory-Browsing-in-ASP-Net
The problem is that every time I click on a node, it calls postback, which refreshes the page. So how do I stop postback being called every time?
<asp:TreeView ID="TreeView1" runat="server" Height="326px" ImageSet="XPFileExplorer"
NodeIndent="15" Width="292px">
<ParentNodeStyle Font-Bold="False" />
<HoverNodeStyle Font-Underline="True" ForeColor="#6666AA" />
<SelectedNodeStyle BackColor="#B5B5B5" Font-Underline="False" HorizontalPadding="0px"
VerticalPadding="0px" />
<NodeStyle Font-Names="Tahoma" Font-Size="8pt" ForeColor="Black" HorizontalPadding="2px"
NodeSpacing="0px" VerticalPadding="2px" />
<LeafNodeStyle ImageUrl="../images/folder.gif" />
</asp:TreeView>
Code behind:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
TreeNode onjParent = new TreeNode("C:\\", "C:\\");
onjParent.PopulateOnDemand = true;
TreeView1.Nodes.Add(onjParent);
TreeView1.CollapseAll();
}
error.Visible = false;
TreeView1.TreeNodeExpanded += new TreeNodeEventHandler(TreeView1_TreeNodeExpanded);
TreeView1.SelectedNodeChanged += new EventHandler(TreeView1_SelectedNodeChanged);
}
void TreeView1_SelectedNodeChanged(object sender, EventArgs e)
{
_browseTextBox.Text = TreeView1.SelectedValue;
}
void TreeView1_TreeNodeExpanded(object sender, TreeNodeEventArgs e)
{
if (e.Node.Value.EndsWith("\\"))
{
AddNodes(e.Node.Value, e.Node);
}
}
private TreeNode AddNodes(string path, TreeNode parentNode)
{
FileList objList = new FileList(path, "*.*");
TreeNode node = new TreeNode(path, path);
for (int index = 0; index < objList.Directories.Length; index++)
{
string directory = objList.Directories[index];
TreeNode objChildNode = new TreeNode(directory, path + "\\" + directory + "\\");
objChildNode.PopulateOnDemand = true;
objChildNode.Target = "_blank";
parentNode.ChildNodes.Add(objChildNode);
}
foreach (string file in objList.Files)
{
TreeNode objChildNode = new TreeNode(file, path + "\\" + file);
parentNode.ChildNodes.Add(objChildNode);
}
return node;
}
protected void _browseButton_Click(object sender, ImageClickEventArgs e)
{
TreeView1.Nodes.Clear();
if (UpdateBrowseTextBoxWithSlash())
{
TreeNode onjParent = new TreeNode(_browseTextBox.Text, _browseTextBox.Text);
onjParent.PopulateOnDemand = true;
TreeView1.Nodes.Add(onjParent);
TreeView1.CollapseAll();
}
else
{
error.Visible = true;
error.Text = "Please Enter valid path";
}
}
private bool UpdateBrowseTextBoxWithSlash()
{
if (_browseTextBox.Text.Length != 0)
{
if (
-1 == _browseTextBox.Text.LastIndexOf(".") &&
!_browseTextBox.Text.Substring(_browseTextBox.Text.Length - 1, 1).Equals("/") &&
!_browseTextBox.Text.Substring(_browseTextBox.Text.Length - 1, 1).Equals("\\")
)
{
if (_browseTextBox.Text.Substring(0, 1).Equals("\\") || -1 != _browseTextBox.Text.IndexOf(":\\"))
_browseTextBox.Text += "\\";
else
_browseTextBox.Text += "/";
return System.IO.Directory.Exists(_browseTextBox.Text);
}
else if (_browseTextBox.Text.LastIndexOf(".") > 0)
{
return System.IO.File.Exists(_browseTextBox.Text);
}
}
return true;
}
Have you looked at Imperfect Solution To TreeView? The author provides an interesting idea to omit postback when selecting a node by manually setting the NavigateUrl and SelectAction of each TreeNode. From first glance, it appears logical. The only thing missing is that it is not recursive so it can only handle one node level at a time.

ListBox, get selected item issue

I'm new to C# asp.net and I'm having trouble getting the selected item. Here is the code behind:
List<string> figuritasSelecionadas = new List<string>();
this.lblMensaje.Visible = false;
decimal total = 0;
foreach (ListItem lf in this.ListaFiguritas.Items)
{
if (lf.Selected)
{
figuritasSelecionadas.Add(lf.Text);
total += Decimal.Parse(lf.Value);
}
}
The problem here is that it doesn't matter which item is selected, because when it reaches the if the first item is marked as true. And I have no idea why it's doing this.
Here is how I load the ListBox:
private void cargarFiguritas()
{
List<Figurita> figuritas = Sistema.Instancia.figuritasQueFaltan(usuarioActivo);
this.ListaFiguritas.DataSource = figuritas;
this.ListaFiguritas.DataValueField = "Precio";
this.ListaFiguritas.DataTextField = "NumeroFigurita";
this.ListaFiguritas.DataBind();
Session["ListaFiguritas"] = figuritas;
}
protected void Page_Load(object sender, EventArgs e)
{
usuarioActivo = (string)Session["nombreUsuario"];
this.lblUsuario.Text = (string)Session["nombreUsuario"] + " tiene un total de: " + Session["Monedas"].ToString() + " monedas";
if (!IsPostBack)
{
cargarFiguritas();
}
}
Here is the aspx code:
<asp:ListBox ID="ListaFiguritas" runat="server" Height="180px" Width="110px" SelectionMode="Single">
</asp:ListBox>

List stays populated after PostBack

I have a .aspx application where the user inputs a name and that name is added to a list. This can be done up to five times. When the user clicks the button, the first name entered will display in the first label. When the user inputs another name and clicks the button the first label remains the same and the next label displays the new name and so on. My problem is the list is reset on PostBack. I am trying to use ViewState to help solve this with no success. Any help is greatly appreciated.
Edit: I got it working so thank you everybody for your help. There is still a lot of room for improvement but this is a great starting point.
[Serializable]
class Recipient
{
public string Fname { get; set; }
public string MInit { get; set; }
public string Lname { get; set; }
public string Suffix { get; set; }
}
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnEnter_Click(object sender, EventArgs e)
{
Recipient recipients = new Recipient();
List<string> FName = (List<string>)ViewState["recipientList"];
List<string> MInit = (List<string>)ViewState["recipientList"];
List<string> LName = (List<string>)ViewState["recipientList"];
if (FName == null && MInit == null && LName == null)
{
FName = new List<string>();
MInit = new List<string>();
LName = new List<string>();
}
recipients.Fname = txtFName.Text;
recipients.MInit = txtMinit.Text;
recipients.Lname = txtLName.Text;
FName.Add(recipients.Fname);
MInit.Add(recipients.MInit);
LName.Add(recipients.Lname);
ViewState["recipientList"] = FName;
ViewState["recipientList"] = MInit;
ViewState["recipientList"] = LName;
if (FName.Count == 1 && MInit.Count == 1 && LName.Count == 1)
{
lblFName.Text = FName[0] + " " + MInit[0] + " " + LName[0];
}
if (FName.Count == 4 && MInit.Count == 4 && LName.Count == 4)
{
lblFName1.Text = FName[1] + " " + MInit[2] + " " + LName[3];
}
}
I'm not sure the purpose of Recipient class. Anyhow, you want to instantiate Recipient list before adding a recipient.
<asp:TextBox runat="server" ID="txtFName" /><br />
<asp:Button runat="server" ID="btnEnter" Text="Submit" OnClick="btnEnter_Click" /><br />
<asp:Label runat="server" ID="lblFName" /><br />
<asp:Label runat="server" ID="lblFName1" /><br />
<asp:Label runat="server" ID="lblFName2" /><br />
<asp:Label runat="server" ID="lblFName3" /><br />
<asp:Label runat="server" ID="lblFName4" /><br />
[Serializable]
public class Recipient
{
public string name { get; set; }
}
public List<Recipient> recipientList
{
get
{
if (ViewState["recipientList"] != null)
return (List<Recipient>)ViewState["recipientList"];
return new List<Recipient>();
}
set { ViewState["recipientList"] = value; }
}
protected void btnEnter_Click(object sender, EventArgs e)
{
List<Recipient> recipient = recipientList;
recipient.Add(new Recipient{ name = txtFName.Text.Trim()});
recipientList = recipient;
int count = recipient.Count;
if (count == 1)
lblFName.Text = recipientList[0].name;
if (count > 1)
lblFName1.Text = recipientList[1].name;
if (count > 2)
lblFName2.Text = recipientList[2].name;
if (count > 3)
lblFName3.Text = recipientList[3].name;
if (count > 4)
lblFName4.Text = recipientList[4].name;
}
Do you really need a list for this? You could do...
if(lblFName.Text.Equals(String.Empty))
{
lblFName.Text = value;
}
else if(lblFName1.Text.Equals(String.Empty))
{
lblFName1.Text = value;
}//and so on...
If a postback is firing when you hit the enter button. Then you need to handle rebuilding the list in the Page_Load. Something like this:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
recipientList = (List<string>)ViewState["recipientList"];
//now load the list
}
}

Select all CheckBoxes in CheckBoxList

I have a CheckBox and a CheckBox list on my web page.
If the CheckBox is selected, all the CheckBoxes in the CheckBoxList should get selected, and if the CheckBox is unchecked, similarly all the CheckBoxes in the CheckBox should get deselected (unchecked).
.aspx code
<asp:CheckBoxList ID="CheckBoxList1" runat="server"
RepeatDirection="Horizontal" RepeatLayout="Flow">
<asp:ListItem>Item A</asp:ListItem>
<asp:ListItem>Item B</asp:ListItem>
<asp:ListItem>Item C</asp:ListItem>
<asp:ListItem Selected="True">Item D</asp:ListItem>
<asp:ListItem>Item E</asp:ListItem>
<asp:ListItem>Item F</asp:ListItem>
<asp:ListItem>Item G</asp:ListItem>
</asp:CheckBoxList>
<asp:CheckBox ID="allChkBox" Text="Select all" runat="server"
oncheckedchanged="allChkBox_CheckedChanged" />
I tried by doing somehting like this, but it didb't work:
bool prevSelection = false;
protected void allChkBox_CheckedChanged(object sender, EventArgs e)
{
if (!prevSelection)
{
foreach (ListItem chkitem in CheckBoxList1.Items)
{
chkitem.Selected = true;
}
}
else
{
foreach (ListItem chkitem in CheckBoxList1.Items)
{
chkitem.Selected = false;
}
}
prevSelection = !prevSelection;
}
I prefer to use client script for something like this so your page doesnt have to do a postback
If that is a possibility try firing a javascript function on click to do the looping and selecting ... something like
<script type="text/javascript">
checked=false;
function checkedAll (frm1) {
var aa= document.getElementById('frm1');
if (checked == false)
{
checked = true
}
else
{
checked = false
}
for (var i =0; i < aa.elements.length; i++)
{
if(aa.elements[i].type == 'checkbox') {
aa.elements[i].checked = checked;
}
}
}
</script>
It's been a while since I've dabbled in ASP.NET, but your prevSelection field will be initialized to false on each and every request. That value will not be persisted between requests. So, you either need to store it in View State or the cache and load it from there in your event handler, or, even better, change your method to something like this:
protected void allChkBox_CheckedChanged(object sender, EventArgs e)
{
foreach (ListItem chkitem in CheckBoxList1.Items)
{
chkitem.Selected = allChkBox.Selected;
}
}
How about this Iif I have understood the requirement right!)? This will make all items selected in a CheckBoxList control by default when it renders:
protected void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostBack) return;
LoadCountryList();
}
private void LoadCountryList()
{
_ctx = new PayLinxDataContext();
chkCountries.DataSource = _ctx.Countries.OrderBy(c => c.Name);
chkCountries.DataBind();
foreach (ListItem item in chkCountries.Items)
{
item.Selected = true;
}
}
Instead of using a variable outside the function, how about using the checkbox itself:
protected void allChkBox_CheckedChanged(object sender, EventArgs e)
{
CheckBox chkbox = sender;
foreach (ListItem chkitem in CheckBoxList1.Items)
{
chkitem.Selected = chkbox.Selected;
}
}
you can do it with linq like this
var allChecked = (from ListItem item in CheckBoxList1.Items
where item.Selected
select int.Parse(item.Value)).ToList();
var all = (from ListItem item in CheckBoxList1.Items
select int.Parse(item.Value)).ToList();
function CheckUnCheckAll()
{
var list = document.getElementById("<%=DataList1.ClientID%>") ;
var chklist = list.getElementsByTagName("input");
for (var i=0;i<chklist.length;i++)
{
if (chklist[i].type=="checkbox" )
{
chklist[i].checked = checkoruncheck;
}
}
}

Categories