How to change Individual Lineitems fonts for Checkboxlist? - asp.net

I am using a checkboxlist which I am populating from the database using Databind(). And i am having Dropdownlist in UpdatePanel to avoid postbacks which is also populated form database. Each Item in dropdownlist-> Associated to Many Items in Checkboxlist. Is there any way I can Make Associated listitems bold(to highlight them) on Dropdown Selected Index Changed Event so that user will know he has to select the highlighted checkboxes for the selected value in dropdownlist?
I have tried using the listitem Attributes as well but it's not working. See the code below.
protected void LOSDropDownList_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
string selectedValue = LOSDropDownList.SelectedValue;
LOSQuestionsBOReadOnlyList QuestionList = LOSQuestionsBOReadOnlyList.GetLOSQuestionsBOReadOnlyListByLevelOfServiceId(Convert.ToInt32(selectedValue));
if (!selectedValue.Equals(""))
{
foreach (ListItem Item in QuestionCheckboxList.Items)
{
Item.Attributes.CssStyle.Clear();
if(QuestionList.FirstOrDefault(Val => (Val.ServiceLevelQuestion_ID == int.Parse(Item.Value.ToString()))) == null)
{
Item.Attributes.CssStyle.Add("font-weight", "bold");
}
else Item.Attributes.CssStyle.Add("font-weight", "normal");
}
}
}
catch (Exception ex)
{
ExceptionPolicy.HandleException(ex, "Event_File_Policy");
}
}
Your help will be appreciated
Thanks And Regards,
Chetan

Try this:
On the SelectedIndexChanged event of dropdownlist:
foreach(ListItem li in chkboxlist.Items)
{
//If dropdownlist selection matches with chklistbox (or whatever other logic you want)
if(li.Text == dropdownlist.SelectedText)
{
**//Here's how to set it to bold**
li.Attributes.CssStyle.Add("font-weight", "bold");
}
}

Related

ASP.NET: Custom CheckBoxList control losing checked state on postback

I extended the ASP.NET CheckBoxList web control to create a Bootstrap 5 layout version.
The control works fine, but on postback, it loses the checked state. Also, the control's SelectedItem property is null.
I created the same control for the RadioButtonList and it works perfectly. Using DotPeek, I see that both of those inherit the same controls and interfaces, so I can't figure out why the custom RadioButtonList maintains state but the CheckboxList doesn't.
Any ideas? The internet has no useable examples to speak of.
C#
public class Bootstrap5CheckBoxList : CheckBoxList {
protected override void Render(HtmlTextWriter writer) {
try {
var selected = false;
//var webControl = new WebControl(HtmlTextWriterTag.Div);
//webControl.ID = ClientID;
//webControl.RenderBeginTag(writer);
for (int index = 0; index < Items.Count; index++) {
var item = this.Items[index];
//div
writer.Indent++;
writer.WriteBeginTag($"div class='form-check {base.CssClass}'");
writer.Write('>');
writer.WriteLine();
//input
writer.Indent++;
writer.WriteBeginTag("input");
writer.WriteAttribute("id", $"{this.ID}_{index}");
writer.WriteAttribute("type", "checkbox");
writer.WriteAttribute("name", $"{this.UniqueID}_{index}");
var cssClass = "";
if (item.Attributes["class"] != null) {
cssClass = item.Attributes["class"];
}
writer.WriteAttribute("class", $"form-check-input {cssClass}");
writer.WriteAttribute("value", item.Value);
var clientID = this.ClientID;
if (item.Selected) {
if (selected) {
this.VerifyMultiSelect();
}
selected = true;
writer.WriteAttribute("checked", "checked");
}
if (item.Attributes.Count > 0) {
foreach (string key in item.Attributes.Keys) {
if (!"class".Equals(key)) {
writer.WriteAttribute(key, item.Attributes[key]);
}
}
}
if (!item.Enabled)
writer.WriteAttribute("disabled", "disabled");
if (this.Page != null) {
this.Page.ClientScript.RegisterForEventValidation(
this.UniqueID,
item.Value);
}
writer.Write('>');
writer.WriteEndTag("input");
writer.WriteLine();
//label
writer.WriteBeginTag("label");
writer.WriteAttribute("class", "form-check-label");
writer.WriteAttribute("for", $"{this.ID}_{index}");
writer.Write('>');
HttpUtility.HtmlEncode(item.Text, writer);
writer.WriteEndTag("label");
writer.Indent--;
writer.WriteLine();
//Close Div
writer.WriteEndTag("div");
writer.WriteLine();
writer.Indent--;
}
//webControl.RenderEndTag(writer);
} catch (Exception ex) {
throw new Exception(string.Format("{0}.{1}:{2} {3}", System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.FullName, System.Reflection.MethodBase.GetCurrentMethod().Name, ex.Message, ex.StackTrace));
}
}
}
HTML
<%# Register TagPrefix="BSControls" Namespace="My.App.classes.custom_controls" Assembly="My.App" %>
<BSControls:Bootstrap5CheckBoxList ID="customCheckList" runat="server">
<asp:ListItem Value="1">Check 1</asp:ListItem>
<asp:ListItem Value="2">Check 2</asp:ListItem>
</BSControls:Bootstrap5CheckBoxList>
looks like you now using html controls, and they don't have automatic viewstate. you would be MUCH better to use a CheckBox list, and format that with bootstrap. And it also FAR better to include that checkbox list in the user control markup, and not write code to inject such controls if possible.
So, plain jane check box (input type = checkbox) as a general rule does not have automatic view state like asp.net controls. So, either drop in a check box list into your user control markup, or you may well have to add code to save/restore the values, since it looks much like you are injecting the "input" control as opposed to using a asp.net checkbox list.
After many trials, I was able to get this working and the answer is surprisingly, or maybe not, simple.
The 'name' attribute is the key and must be in the correct format.
Incorrect Format
writer.WriteAttribute("name", $"{this.UniqueID}_{index}");
Correct Format
writer.WriteAttribute("name", $"{this.UniqueID}${index}");
You must use the $ separator and not an underscore. On postback, the LoadPostData method in CheckBoxList iterates through a collection to retrieve the check state.

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?

How to Find Control in Datalist1?

Hi can anybody tell how i can find a DataList which is inside the DataList control?Its giving the Error Object not set to an Instance.
i am finding the control this way :
DataList dl =((DataList) (DataList1.FindControl("DataList2")));
is it the right way?
It depends when you want to find the control and which control. If you just want to get all of them you loop through the DataList Items like below. Say you want to access a CheckBox inside a DataList.
foreach (DataListItem item in DataList1.Items)
{
if (item.ItemType == ListItemType.Item ||item.ItemType == ListItemType.AlternatingItem)
{
CheckBox chb=(CheckBox) item.FindControl("CheckBox1");
if (chb!= null)
{
//you can access chb.Checked value
}
}
}
Is DataList2 directly inside DataList1 or is it inside a child component of DataList1?
The FindControl method does not do a deep search for controls.
I wrote a method to do this a while ago, I'll post it here incase it's of use:
public static IEnumerable<Control>
GetDeepControlsByType<T>(this Control control)
{
foreach(Control c in control.Controls)
{
if (c is T)
{
yield return c;
}
if(c.Controls.Count > 0)
{
foreach (var x in c.GetDeepControlsByType<T>())
{
yield return x;
}
}
}
}

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