How can same user control render different output? - asp.net

Ok. Here we go. I am not sure if anyone here has implemented this, but I have a user control in my Webforms application which I am calling on several forms.
This user control has a dropdown which calls the stored procedure and filters the dropdown according to a certain date. However, on one of the forms, I want same user control to still call the stored procedure but not filter at all, just fetch all records.
Basically, I want same user control to do one thing on one form and another thing on another form. I want to use same user control since there is only small change. Rest is the same and hence I want to avoid creating another form.
Is this possible?
Thank you.

The easiest way is create a property on the user control:
public bool SOmeCOnfigurableSetting
{
get { return ((bool?)ViewState[".."]).GetValueOrDefault(false); }
set { ViewState[".."] = value; }
}
It can be any type, not just bool. In each page, set the property on the user control definition, and this controls the filtering or other functionality.

Related

Maintaining dynamic control state between postbacks

I have a dynamic ASP.NET form which I recreate evertime I postback. My values persist no problem.
I am however having a challenge maintaining attributes on Postback. For example, I have user defined code which may enable or disable a field when someone is first presented with the form. If a user posts the form I need an easy way to make sure the field stays enabled or disabled.
Does this make sense? Is there an easy way to do this?
ViewState is the preferred method of persisting information between postbacks that doesn't need to live beyond the scope of a single page. You can store information pretty easily there.
An easy way to accomplish this is to use a property in the control, or the page that abstracts the use of ViewState from you.
protected Boolean IsFieldVisible
{
get{ return (Boolean)ViewState["SomeUniqueKey"] ?? false; }
set{ ViewState["SomeUniqueKey"] = value; }
}
This will maintain the value between postbacks.

Finding and accessing elements of a WebUserControl

I am creating a WebUserControl in ASP.net and want to be able to access elements of that control later. When I access them though I am trying to access them together. For example, adding a CheckBox and a table to a control and then finding the CheckBox, checking whether it has been ticked and if it has been ticked, get the values from the TextBoxes.
I currently have everything loading on the page from the custom controls, but when iterating through the controls on the page, there doesn't appear to be a control of my WebUserControl type. All of the controls are there on the page, but they exist as seperate ASP.net controls.
Am I thinking about this wrong? Is there a better way to do this?
I'm not sure this is explained very well, please feel free to ask clarifying questions.
You need to expose the user controls functionality by making public properties or functions to make it do what you need or act like you want. So for example in your case you could have a property in your user control like (you could also do a function):
public List<string> SomeValues
{
get
{
// return null if checkbox is not checked, you could just as easily return an empty list.
List<string> lst = null;
if (yourCheckBox.Checked)
{
lst = new List<string>();
// You could have something that iterates and find your controls, remember you
// are running this within your user control so you can access all it's controls.
lst.Add(yourTextBox1.Text);
lst.Add(yourTextBox2.Text);
lst.Add(yourTextBox3.Text);
// etc...
}
return lst;
}
}
Then in your page you can access your user control and call this property to get the values:
// assuming you defined your usercontrol with the 'yourUserControl' ID
List<string> lst = yourUserControl.SomeValues;
The key is to just expose what you want IN your user control so whatever is using it doesn't need to know about it's details or implementation. You should be able to just use it as you would any other control.

asp.net code behind variable

I am generating some head html in page load and because of that I query database once. in the page I query database again and put data into html with inline code.
my question is is there better way to do this? I dont want to query database everytime and reach out those filled variables from inline code. something like page.addVariable in page_load and reach those at inline like page.variables["variablename"]
thanks in advance
If I understand what you are asking, you can make an accessor and set it to Protected. That will allow you to access it from the page.
If you want to prevent calling the database on callbacks, you could always add the information to the view state on the page.
Information on the view state, hidden fields, and cookies:
http://www.csharphelp.com/archives/archive207.html
I'm not sure if this is what you're after, but you can use a HiddenField to store any data you want on the page.
Also, if you don't need it to be on the page, you can use Session or ViewState.
Here's an example of using ViewState as a property (NB. you can interchange ViewState with Session, look at the links I gave you for an explanation between the two):
public string YourProperty
{
get
{
object content = ViewState["YourProperty"];
if (content == null)
{
return string.Empty;
}
return content.ToString();
}
set
{
ViewState["YourProperty"] = value;
}
}
Note, that anything you put into ViewState or SessionState must be marked as Serializable.
If it's quite a simple class, just mark the class with the [Serializable] tag.
Is the data you retrieve from the database page specific, user specific or global to the entire application?
If the data is user specific you can use Session State.
If the data is global to the entire application you could use Application State.
Whichever you use, you can implement the data retrieval in the Session_Start (will be called only once for each user) or Application_Start (will be called only once when the web app starts) events in a Global.asax file.

Copy info from one dynamically created user control to another dynamically created user control

My ASP.NET WebForm has a place holder on it and user controls are dynamically added to it. The controls mostly have textboxes. Sometimes there are two user controls, sometimes there are ten. Everything is working as expected. My question is about how to implement a new feature.
My customer has a new request to copy data from the first control to another control checking a checkbox associated with the additional control in question.
At first, this sounded easy... Add a checkbox to the placeholder for each user control and then write some JavaScript to copy the data from the first control to the additional control. Then I realized that by those textboxes being in a user control, I don't really have access to modify the HTML inputs directly.
Next I started thinking about adding checkboxes that will automatically post back, but how do I go about dynamically adding a checkbox to a placeholder, and then come up with a way to add event handler to the checkbox and pass in the information necessary to loop through the controls and copy the values. This approach seems way too complicated with too much overhead to accomplish my goal.
Any suggestions?
You mentioned that since the checkboxes are in a user control, you don't have access to them.
Could you expose the ClientIDs using a property of the user control and then work with them in javascript? Something like this:
user_control {
int checkboxId { get { return checkbox.ClientId; } }
}
If you have more code that would be helpful...
This is probably too late to help you, but just so another answer is out there...
Including the checkbox as a part of the user control simplifies the issue considerably.
I had a similar situation, with maybe 10-15 UI controls in a user control, with a checkbox associated with the first one which, when checked, meant that I should copy the info from the first user control to all of the others.
Since it was all built in the codebehind, I simply exposed a boolean property of the user control named ShowCheckBox, which toggled the visibility of the checkbox. I set this to true in the first one, and false in all of the others. Thus, I knew that the event could only be raised by a click of the first user control's checkbox. Then, in the event handler for the checkbox, I handled the copying from the first user control to all of the others. (By the way, be sure to set AutoPostBack=true on that checkbox or you'll wonder why the event isn't firing.)
Javascript would definitely provide a better user experience, but this worked for me and didn't require me to figure out how to get the ClientId values into the javascript. (Although that's exactly what I need to do now, which is how I stumbled upon this question. :-) )

ASP.net drop down dynamically styling and then remembering the styles on aborted submit

So, I've got an ASP drop down list (this is .net 2.0). I'm binding it with data. Basically, when the page loads and it's not a post back we'll fetch record data, bind all the drop downs, and set them to their appropriate values (strictly speaking we: initialize page with basic set of data from DB, bind drop downs from DB, fetch actual record data from DB, set drown downs to appropriate settings at this time). What I want to do is selectively style the list options. So the database returns 3 items: ID, Text, and a flag indicating whether I the record is "active" (and I'll style appropriately). It's easy enough to do and I've done it.
My problem is what happens when a form submission is halted. We have slightly extended the Page class and created an AddError() method, which will create a list of errors from failed business rule checks and then display them in a ValidationSummary. It works something like this, in the submit button's click event:
CheckBizRules();
if(Page.IsValid)
{
SaveData();
}
If any business rule check fails, the Page will not be valid. The problem is, when the page re-renders (viewsate is enabled, but no data is rebound) my beautiful conditional styling is now sadly gone, off to live in the land of the missing socks. I need to preserve it.
I was hoping to avoid another DB call here (e.g. getting the list data back from the DB again if the page isn't valid, just for purposes of re-styling the list). But it's not the end of the world if that's my course of action. I was hoping someone might have an alternative suggestion.
I couldn't think of how to phrase this question better, if anyone has any suggestions or needs clarification don't hesitate to get it, by force if need be. ;)
I'm not sure I completelly understand what kind of styling you apply to your drop-down items, but it seems this style is something that the control does not preserve accross postbacks. Usually this kind of info will therefore need to be saved in the ViewState.
I see two options (other than re-loading from DB):
First method: Create your own drop-down control that inherits from DropDownList. Then save styling data in the control's ViewState bag when styling the items:
public void SetItemActive(ListItem item)
{
ViewState[item.Value] = "active";
}
then override the OnRender
protected override void Render(HtmlTextWriter writer)
{
....
foreach(ListItem item in Items)
{
if ( ViewState[item.Value] == "active")
{
** RenderActiveItem **
}
else
{
** RenderNormalItem **
}
}
Second method: is to save the active ID's in the Page's ViewState then re-style the dropdown on each postback using the data from the ViewState rather than from the DB
Well, I couldn't come up with anything except to go to the database to re-retrieve my list data when the Page was not valid, and re-style the control.

Resources