Making a treeview mimic required field validator functionality - c#

I am in need of validating a TreeView to make sure that users have selected something. What I need is something that mimics a RequiredFieldValidator and stops a page from posting back with any data until something is selected.
I am using C# and ASP.NET 3.5
I have tried this and it did not work for me:
if (TreeView.SelectedNode.Value == null)
{
lblError.Text = "Required";
lblError.ForeColor = Color.Red;
}
I am at a loss, and any help would be very appreciated.

As far as I can say, TreeView is basically used for navigation and in navigation you cannot force a user to choose node. But if its requirement in your app. If your are navigating to other page, then you can do one thing, add some flag or value to your querystring so that the app will know whether its coming from treeview or directly by copy pasting the url. Catch it all in your Page_Load event.
or Create a Session variable in the treeview selected event Session["TreeviewChecked"]= true;
In your code check if Session is null or not.
I hope this will help.

Related

Asp.net controls not updating after a postback

I'm writing code to read data from asp controls to update records in a database. I've been debugging the last day and I've tracked it back to something that I ought to have noticed before.
The code first populates the controls with the existing values from the database.
When I click SAVE, it should read the current values from the controls and save with those.
Unfortunately, what it's actually doing is using the values of the controls before a change was made to them. It's not seeing the change to the controls.
Here's a sample:
<asp:TextBox ID="OtherCourseName_5" runat="server"></asp:TextBox>
Here's the corresponding behind code in the btnSave_onClick() function:
int object_number=5;
string other_course_name_string
= "OtherCourseName_" + object_number.ToString().Trim();
TextBox ocn = utilities
.utils
.FindControlRecursive(this.Master, other_course_name_string) as TextBox;
I'm using the FindControlRecursive() I found somewhere on the web. It works, I'm sure, but just in case, I tried to address the control directly as OtherCourseName_5.Text.
Even if I just display the value in OtherCourseName_5.Text, it gives the original value.
I use this same page for both entering new data and for editing data. It works fine when I enter the data. That is, it correctly sees that the TextBox control has changed from empty to having data. It's only when I invoke the edit function on the page (by passing edit=true). I invoke it this way by adding the switch edit=true as a query string (the program correctly reads that switch, gets to the appropriate area of code, prints out all the correct values for everything - except the contents of the controls!).
The page is far too complicated to post the entire thing. I've tried to convey the essential details. It's entirely possible that I've made a simple coding error, but it's seeming more a possibility that I fundamentally misunderstand how pages are processed.
Is there anything known that can make it seem as though the value of a control has not been changed?
Note 1: I thought perhaps I had to go to another field after I entered the data, but I tried that and it's still a problem.
Note 2: I'm using both TextBox and DropDownList controls and have the same problem with both.
Note 3: These controls are on a panel and the page is using a SiteMaster. I haven't had any problem with that and don't think the problem is there, but I'm down to questioning the laws of the physics at this point.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
//populate controls with data from database
}
}
When you do a postback before the postback handler is evaluated the PageLoad event is raised
so if you don't avoid to rebind your control they will be loaded with the values from the database. And then the postback event will save them to db
Asp.net Page Lifecycle
(source: microsoft.com)

ASP.NET SetFocus works on Localhost but not working on Server

I have a website that is working well, except for one problem. I have a text field which takes in ID value of the member and populates the details of the member.
When I try to fetch details of a user, the Cursor should automatically show up in the textbox, whether the results were found or not. This works perfectly on the localhost project but doesnt work on the Production.
Using ASP.NET and C# for this.
Control textControl = FindControl("txtIDValue");
if (textControl != null)
{
ScriptManager.GetCurrent(this.Page).SetFocus(textControl);
}
The above is the code I use. Can someone please help me? I have been struggling with this past 2 days!
Try this instead:
TextBox textControl = (TextBox)this.FindControl("txtIDValue");
if (textControl != null)
{
textControl.Focus();
}
This way you don't use the ScriptManager and cast the control to a TextBox.

Dynamic controls in updatepanel not posting in Opera Mobile

I have a page to which I am adding a dynamic UpdatePanel with more dynamic controls in it's ContentTemplateContainer. ViewState is disabled on the ContentTemplateContainer because the entire state can be recreated on postbacks from a single ID in a HiddenField like so:
if (request.HttpMethod == "POST")
{
string ctrlName = request.Params.Get("__EVENTTARGET");
int yearID = int.Parse(request.Form["hfPrevYear"]);
if (!string.IsNullOrEmpty(ctrlName) && ctrlName == "btnYearUp")
{
yearID = getNextDataYear(di.getTestData(), yearID);
}
else if (!string.IsNullOrEmpty(ctrlName) && ctrlName == "btnYearDown")
{
yearID = getPrevDataYear(di.getTestData(), yearID);
}
}
The problem is that Opera Mobile is not posting the hidden field, causing my page to throw an exception when it tries to parse that value. It only posts controls outside the update panel like the hidden fields that ASP.NET adds for viewstate and event target. When I was stepping through the postback code in Dragonfly, I notice that the document.forms[0].elements[] collection doesn't include my controls, which is what the updatepanel code loops through to build the post request.
Other browsers post the field just fine, including Opera Mini and Desktop Opera.
Any idea what's going on here?
Thanks for the help,
--Nick
Since you haven't posted an example, I can only give you some general tips. My best guess is that the core version of Opera mobile may have a bug that's already fixed in Opera desktop/Mini.
Make sure your markup inside the form is correct - if tags are in the wrong order somewhere, for example something like
<p><b></p></b>
it can confuse the parser, and an example of such confusion might be that a form is closed too early and controls end up "outside" it. The validator.w3.org service can help you find such problems.
Also, check that tags that need closing do have a closing tag, for the same reason.
How are the elements added to the form - are they in the markup from the beginning, or added with JavaScript? If the latter, try adding them to the form itself explicitly (document.forms[x].appendChild().. rather than appending them to an element you think is inside the form).

javascript viewstate problem

I have a situation that I am stuck with, and hoping someone can help. I am building a .NET/C# web application in which I have a tabbed panel layout, and when the user clicks on each of the tabs the display panel is updated using javascript to hide and show some divs. None of these clicks cause postback, it is all client-side, so I can't use viewstate or session.
What I want to do is somehow remember which panel was last visible when the page is refreshed, yet without posting back to the server I am unsure how to do this. I have tried a hidden field but obviously its value is reset every time because the form is never submitted. I do know that I can achieve this using cookies but its a little annoying to implement for such a (seemingly) trivial operation ... but maybe this is the only way?
Does anyone have any more elegant solution to this problem?
Using a function like this to show and hide tabs):
function makeCurrent(tab) {
if (tab.title == 'Manage orders') {
document.getElementById('panelOrders').style.display = "block";
// Hide others
document.getElementById('panelAccounts').style.display = "none";
document.getElementById('panelProducts').style.display = "none";
document.getElementById('panelSettings').style.display = "none";
// Remember last viewed panel
document.getElementById('hdnCurrentlyViewing').value = "orders";
}
The panels are just divs with style.display controlling their visibility. Not sure if its useful to post HTML code because its fairly self explanatory ...?
You can make this happen without a postback is to make an AJAX call from Javascript where you tell your server what the current panel is as you switch it.
I prefer using a framework like JQuery or Prototype to help make these AJAX calls myself.
I think Hidden field will be the best option. have you tried ASP:HiddenField? It can be accessed across postbacks.
But if you still have some reservations with postbacks and hiddenfield you can also use cookies from JS http://techpatterns.com/downloads/javascript_cookies.php this is helper lib for cookies manipulation within JS.
Regards.

URL and Query management Asp.Net C#

Ok so while back I asked question Beginner ASP.net question handling url link
I wanted to handle case like this www.blah.com/blah.aspx?day=12&flow=true
I got my answer string r_flag = Request.QueryString["day"];
Then what I did is placed a code in Page_Load()
that basically takes these parameters and if they are not NULL, meaning that they were part of URL.
I filter results based on these parameters.
It works GREAT, happy times.... Except it does not work anymore once you try to go to the link using some other filter.
I have drop down box that allows you to select filters.
I have a button that once clicked should update these selections.
The problem is that Page_Load is called prior to Button_Clicked function and therefore I stay on the same page.
Any ideas how to handle this case.
Once again in case above was confusing.
So I can control behavior of my website by using URL, which I parse in Page_Load()
and using controls that are on the page.
If there is no query in URL it works great (controls) if there is it overrides controls.
Essentially I am trying to find a way how to ignore parsing of url when requests comes from clicking Generate button on the page.
Maybe you can put your querystring parsing code into IsPostBack control if Generate button is the control that only postbacks at your page.
if (!IsPostBack)
{
string r_flag = Request.QueryString["day"];
}
As an alternative way, at client side you can set a hidden field whenever user clicks the Generate button, then you can get it's value to determine if the user clicked the Generate button and then put your logic there.

Categories

Resources