Determining which checkbox is checked in a checkboxlist list - asp.net

I've a asp.net page which uses multi select checkboxlist(say having 10 checkboxes)....for example
I've enabled AutoPostBack for any change in checkboxlist.
Initially,out of 10, 3 are selected.
On top of this, if user checks another checkbox, how do I know which particular checkbox has been checked by the user and retrieve its value?
Thanks.

for (int i=0; i<checkboxlist1.Items.Count; i++)
{
if (checkboxlist1.Items[i].Selected)
{
}
}
protected void Page_Load(object sender, EventArgs e)
{
string name = Request.Form["__EVENTTARGET"] ?? String.Empty;
if (name.IndexOf("CheckBoxList1") != -1)
{
int last = name.LastIndexOf("$") + 1;
int index = Convert.ToInt32(name.Substring(last, name.Length - last - 1));
if (CheckBoxList1.Items[index].Selected)
{
string text = CheckBoxList1.Items[index].Text;
string value = CheckBoxList1.Items[index].Value;
}
}
}

If you want to know which last checkbox was clicked on the server side, you should enable AutoPostBack for each checkbox and capture the values accordingly. If you have the flexibility to find out the last checkbox click on the client side, then you should implement a javascript "onclick" event for each checkbox to capture the value on each checkbox and simply update the checked value in a hidden variable and pass it back to the server on postback

Related

Disable/Enable save button based on the mandatory field being null or empty using Behaviors

I created a behavior 'RequiredValidationBehavior' and applied to one of the entry fields in XAML page.
It works as, if the entry field is empty, the placeholder color becomes red, thus indicating the mandatory field. This works fine.
The issue I am facing is with the button on the page, where it should to be disabled if this entry field is empty and enabled if the entry field has some value.
I want to achieve this using the behavior I created.
Thanks for the responses in advance.
You can try with below code:
public void entryTextChanged(object obj, EventArgs args)
{
if (entry.Text.Length > 0)
button.IsEnable= true;
else
button.IsEnable = false;
}
And just assign this event to Entry on "TextChanged" Event.
private void EntryMessage(object sender, EventArgs e)
{
var keyword = Message.Text;//your entry
if (string.IsNullOrEmpty(keyword))
{
OnAddBT.IsEnabled = false;//your button
}
else
{
OnAddBT.IsEnabled = true;//your button
}
}

How to hide and display item templates in formview depending on some conditions?

Here I am getting some values from previous page using session to check the condition:
string PTN = Session["PrimaryTool"].ToString();
string PTE = Session["PrimaryToolExp"].ToString();
if (PTN != null && PTE != null)
{
if (fvJobApplying.CurrentMode == FormViewMode.ReadOnly)
{
Label PT = (Label)fvJobApplying.FindControl("lblPrimaryTool");
PT.Visible = true;
Label PTExperience = (Label)fvJobApplying.FindControl("lblPrimaryToolExp");
PTExperience.Visible = true;
Label Experience = (Label)fvJobApplying.FindControl("lblExperience");
Experience.Visible = false;
}
}
My session values and my condition works fine... Here depending on condition how to show and hide columns or item templates in formview in asp.net
It's not clear what problem/error you actually have, however...
Don't use Page_Load to bind or access your FormView, instead use the FormView's DataBound event and the CurrentMode property:
protected void fvJobApplying_DataBound(object sender, System.EventArgs e)
{
if(fvJobApplying.CurrentMode == FormViewMode.ReadOnly)
{
// here you can safely access the FormView's ItemTemplate and it's controls via FindControl
Label PT = (Label)fvJobApplying.FindControl("lblPrimaryTool");
PT.Visible = true;
}
else if(fvJobApplying.CurrentMode == FormViewMode.Edit)
{
// here you can safely access the FormView's EditItemTemplate and it's controls via FindControl
}
else if(fvJobApplying.CurrentMode == FormViewMode.Insert)
{
// here you can safely access the FormView's InsertItemTemplate and it's controls via FindControl
}
}
So find your labels there and set the desired Visibility. This event is triggered when you DataBind the FormView.

Need help removing this fudged code... Binding user control on postback

As per the title, I know the code I've posted below is utter poo, this is why I need your help!
I've put way too many hours into this, and it's either down to inexperience, a bug or I've screwed up somewhere.
I have a user control with a view properties that access the ViewState and two user controls within that display the properties.
Within the page_load of the user control, depending on the value of some of the properties, it will toggle the visibility of the controls within:
public partial class PatientStatus : System.Web.UI.UserControl
{
public string PatientName { get { return ViewState["PatientName"] as string; } set { ViewState["PatientName"] = value; } }
public bool ClinicianView { get { return Convert.ToBoolean(ViewState["ClinicianView"]); } set { ViewState["ClinicianView"] = value; } }
public string RangeTitle { get { return ViewState["RangeTitle"] as string; } set { ViewState["RangeTitle"] = value; } }
public int? RangeLimitNormSys { get { return ViewState["RangeLimitNormSys"] as int?; } set { ViewState["RangeLimitNormSys"] = value; } }
public int? RangeLimitNormDia { get { return ViewState["RangeLimitNormDia"] as int?; } set { ViewState["RangeLimitNormDia"] = value; } }
protected void Page_Load(object sender, EventArgs e)
{
bool ispostback = IsPostBack;
if (ispostback && ((System.Web.UI.WebControls.Repeater)(this.Parent.Parent)).DataSource != null)
{
object itm = ((RepeaterItem)this.Parent).DataItem;
if (itm is AppointmentRow)
{
AppointmentRow row = itm as AppointmentRow;
PatientName = row.Name;
RangeTitle = row.Range;
RangeLimitNormDia = row.RangeLimitNormDia;
RangeLimitNormSys = row.RangeLimitNormSys;
ispostback = false;
}
else if (itm is ReadingRow)
{
ReadingRow row = itm as ReadingRow;
PatientName = row.Name;
RangeTitle = row.Range;
RangeLimitNormDia = row.RangeLimitNormDia;
RangeLimitNormSys = row.RangeLimitNormSys;
ispostback = false;
}
else if (itm is PatientRow)
{
PatientRow row = itm as PatientRow;
PatientName = row.Name;
RangeTitle = row.Range;
RangeLimitNormDia = row.RangeLimitNormDia;
RangeLimitNormSys = row.RangeLimitNormSys;
ispostback = false;
}
}
if (!ispostback)
{
if (!string.IsNullOrWhiteSpace(RangeTitle))
{
placeHolder.Visible = true;
literalNA.Visible = false;
}
}
}
}
Previously the Page_Load event simply contained:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
if (!string.IsNullOrWhiteSpace(RangeTitle))
{
placeHolder.Visible = true;
literalNA.Visible = false;
}
}
}
But on postback, the RangeTitle property was always null, so even when removing the isPostBack statement, it didn't work property.
The only way to resolve it, was to really fudge it by the first block of code.
On the Page_Load of the parent page, and on !isPostBack I'm calling a method that gets and binds data to the repeater. This works fine. But on a postback, i'm calling the same method and for some reason, the user control isn't populating.
Any idea's?
Merry Christmas
Gav
Edit
In response to #jwiscarson
I have a table that is generated via an ASP:Repeater and within the ItemTemplate, I have added a User Control which contains a PlaceHolder and a Literal. Also within the User Control is a number of Properties.
Then on databind I pass across a number of values to the user control (I've tried both OnItemDataBound and inline using Eval). Then on the User Control's Page_Load event, as per the second block of code above, I first check if it's a postback, if not, I then check to see if the Property RangeTitle has a value.
If RangeTitle does not have a value, I then hide the placeholder that contains HTML that would display the RangeTitle and show a literal that displays N/A.
When loading the page for the first time, (!isPostBack) it works fine. But as soon as I create a postback, the User Controls within the repeater all revert to N/A even when their RangeTitle properties had a value.
On debugging, I set a breakpoint in the Page_Load of the User Control. When I first load the page, I can see that my properties have been populated correctly. Then on postback, Page_Load is called on the UserControl and the properties are populated correctly, then Page_Load is called again, but this time, the properties are empty.
i.e.
!isPostBack
UserControl::Page_Load < Correct data
isPostBack
UserControl::Page_Load < Correct data
myButton_Click (bind new data)
UserControl::Page_Load < No data
To make things even more confusing. The method called within myButton_Click to bind the data, is the exact same method called in the Page_Load of the Page to populate the repeater on !isPostBack
Thanks ;)
I would check to make sure that DataItem is accessible in this function. I think you need to listen to the ItemDataBound event and perform this work in that event.
Beyond that, it's difficult to suggest anything else concrete. I don't really understand why you're doing what you're doing (if you have this information in a Repeater, why does it also need to be in ViewState?). If you could explain your rationale for doing this, it might help me and anyone else who visits this question. You say that you're just trying to show/hide some specific items on the page. This is pretty complicated code without a lot of justification for that complication.
As an aside: you really, really need to break this code down and think about what you're trying to accomplish. Here are a few suggestions:
Separate the scopes inside your if and else if statements into functions that return the data you need.
Do not include lines like ((System.Web.UI.WebControls.Repeater)(this.Parent.Parent)).DataSource != null in an if statement. Perform this cast separately and store it in a variable, or write a small function that checks this.
Statements like this.Parent.Parent and other references to Parent controls are code smells, in my opinion. Even on a normal page, this would be a code smell, but what exactly is this.Parent going to reference when you include it in a UserControl?

show popupcontrol in rowupdating event of devexpress gridview, if a certain criteria fails

I have a Devexpress Gridview where item and it's price is displayed.
Editing is enabled.
I use rowupdating event so inorder to check if the price updated is higher than a normal value.
if so, i cancel edit by
e.Cancel = true;
ASPxGridView1.CancelEdit();
the next thing i want is to popup a aspx popupcontrol requesting a password inorder to proceed with higher amount within the rowupdating event.
the popcontrol will contain a password textbox and a button.The remaining procces will be carried out by button click function
eventhough i called popcontrol
ASPxPopupControl2.ShowOnPageLoad = true;
the pop doesn't show up......why is this so..
here is my over all code..
protected void ASPxGridView1_RowUpdating(object sender, DevExpress.Web.Data.ASPxDataUpdatingEventArgs e)
{
string msg;
double new_amt = double.Parse(e.NewValues["Amount"].ToString());//-->gets new amount
string type= e.OldValues["Type"].ToString();//-->gets the item
double refer_amt=Misc_functions.Get_Item_Amount(type,out msg);//--this function fetches the normal amount for a particular item
if (new_amt > refer_amt)
{
e.Cancel = true;
ASPxGridView1.CancelEdit();
ASPxPopupControl2.ShowOnPageLoad = true;
}
}
Basically i need a password authentication if an amount edited is a higher than a normal value.
any ideas??
This cannot be done using the server code. The best solution is to create a custom java script variable within the RowUpdating event handler and check its value in the ASPxGridView's client side EndCallback event handler. I.e.
protected void ASPxGridView1_RowUpdating(object sender, DevExpress.Web.Data.ASPxDataUpdatingEventArgs e)
{ ...
gridView.JSProperties["cpShowPopup"] = true;
...
}
EndCallback = function(s,e) {
if(typeof(s.cpShowPopup) != 'undefined') {
popup.Show();
}
}
Hope, this helps.

if i have different asp.net checkboxes in webform with different text as 450, 550, 500, 900

I have different checkboxes in vb.net webform with different text ...
checkbox1.text=100
checkbox2.text=300
checkbox3.text=550 and so on .....
i want when i check checkbox1 and checkbox2 then in textbox1 the text would be 400
means as many as checkbox i select the sun of checkboxes selected will be calculated in textbox using VB.NET ....
i m using Visual Studio 2008
If you are looking at server side code then following code should do the trick:
private int mTotal;
private void EnumerateCheckBoxes(Control control)
{
if (control is CheckBox)
{
var check = (CheckBox)control;
if (check.Checked)
{
int value;
if (int.TryParse(check.Text, out value))
{
mTotal += value;
}
}
}
else if (control.HasControls())
{
foreach(var c in control.Controls)
{
EnumerateCheckBoxes(c);
}
}
}
protected void Page_Load(Object sender, EventArgs e)
{
mTotal = 0;
EnumerateCheckBoxes(this.Form);
textbox1.Text = mTotal.ToString();
}
Although, this is in C#, it should be easy to port to VB.NET. Also few other things to consider:
This code will count radio buttons
as well as because it gets inherited
from CheckBox. If that is to be
avoided then replace if (control is
CheckBox) with if
(control.GetType() ==
typeof(CheckBox))
If you wish to consider checkboxes
from CheckBoxList then you have to
write another condition to see if
control is CheckBoxList and then
within condition, enumerate items
withing checkboxlist. Items count to
be added to total count while
selected items to be added to
checked count.
Use a hidden field and a bit of javascript to set the value, bind this event when a checkbox is checked
function UpdateValue(){
var total= 0;
$('input:checkbox:checked').each(function (i) {
val = total+ int.parse(this.value); //or html
});
$('#hiddenValField').html(total) ;
}

Resources