C# - Clear selected calendar date if it is the same - c#

I have a calendar in my C# code and I want for a date to be deselected if I click on the same date. How to do that?
protected void SelectionChangeCalendar(Object sender, EventArgs e){
selected_date = Calendar1.SelectedDate.ToShortDateString();
if(same date is clicked){
Calendar1.SelectedDates.Clear();
}
}
The problem here is that I believe if the same date is chosen "SelectionChangeCalendar" is not fired.
Markup:
<asp:Calendar ID="Calendar1" runat="server" OnSelectionChanged="SelectionChangeCalendar"></asp:Calendar>

EDIT: Added markup
EDIT: Included fix from yazanpro
You are correct that if you click on the already selected date the OnSelectionChanged event does not fire. It does, however, post back with the event target and event argument just like it would if it were a different date, so you can check for the form arguments and then go from there. The trick was that if you check on page load and then clear the selected date, you end up triggering the OnSelectionChanged event and the date just gets selected again. But if you wait until after the Calender has processed the post back data and decided there was no change, you can successfully clear the date. Here's the code I used to get it to work:
public partial class WebForm1 : System.Web.UI.Page
{
bool clear = true;
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Calendar1_SelectionChanged(object sender, EventArgs e)
{
//if we are here, the date actually changed, so set clear to false
clear = false;
}
protected void Calendar1_PreRender(object sender, EventArgs e)
{
//if clear is true and the event target is the calendar and a date was clicked
if (clear
&& !string.IsNullOrEmpty(Request.Form["__EVENTTARGET"])
&& Request["__EVENTTARGET"].Contains(Calendar1.ID)
&& char.IsDigit(Request.Form["__EVENTARGUMENT"][0]))
{
Calendar1.SelectedDates.Clear(); //clear the date
}
}
}
Markup:
<asp:Calendar ID="Calendar1" runat="server" OnPreRender="Calendar1_PreRender" OnSelectionChanged="Calendar1_SelectionChanged"></asp:Calendar>
The clear variable just keeps track of whether or not the date was actually changed. If it was, the OnSelectionChanged event will fire and we know that we don't have to clear any dates. Here are the steps:
1) When the page posts back, if the event target was the Calendar, the Calendar checks the post data to see if the selection has changed. If it has, it calls the event handler and we set clear = false, meaning we know that a different date was clicked on. If the selection hasn't changed, the Calendar won't fire the even and clear remains true.
2) After the events have been handled, we use the prerender event to check if the event target was the calendar. If it was, and clear is still true, then we know that either the selected date or one of the calendar controls was clicked on. As it turns out, if a control is clicked on, the event argument starts with a letter. If a date was clicked on, it starts with a number (the argument is the number of days since Jan 1, 2000). So all we have to do is check if the first character of the event argument is a digit to see if the currently selected date was clicked on. If so, we clear the date and we're done.
I don't know, it works, but it smells. Maybe there's a better way to do it? It seems though that the Calendar control was not designed to work this way. Anyway, I hope this helps!

protected void Calendar1_SelectionChanged(object sender, EventArgs e)
{
//Check if selected Date is in the saved list
// Remove the Selected Date from the saved list
if (SelectedDates.Contains(Calendar1.SelectedDate))
SelectedDates.Remove(Calendar1.SelectedDate);
else
SelectedDates.Add(Calendar1.SelectedDate);
ViewState["Dates"] = SelectedDates;
}

Related

Repeat same steps on every textChanged event

I have in my project 5 text boxes.
Every TextBox should accept only digits.
For that I created a function which takes not prepared text and returns the proper one.
Now I'm wondering if there is any simpler way to perform this action on every TextBox, on every TextChanged event without repeating almost same code?
private void TextGoldPack_TextChanged(object sender, EventArgs e)
{
(sender as TextBox).Text = Only_digits((sender as TextBox).Text);
}
private void TextGoldTake_TextChanged(object sender, EventArgs e)
{
//repeat here and on every _TextChanged event
}
If I'm understanding you correctly, just because it's named TextGoldTake_TextChanged, doesn't mean that's the only textbox that can use that code. On the events tab, you can set the TextChanged function for all you textboxes to lead to that function. If it helps, rename it something that doesn't sound textbox-specific such as TextChanged.
Change all the TextBoxes to refer this method upon TextChanged.
Use the sender property to get the actual caller TextBox.

DropDownList stuck after using .SelectedValue on him ASP.NET

I'm new with asp.net and i think this is really easy question, but i can't find the answer. I have a DropDownList on my page (that will be page A), one of the ways to go to that page is follow the link on the other page (page B). By this link i deliver some parameters, so i use them in the Page_load of page A:
protected void Page_Load(object sender, EventArgs e)
{
string strStatus = Request.QueryString["status"];
DListStatus.SelectedValue = strStatus;
}
But after it i couldn't choose something else exept this value, sometimes i saw that for a second new item is selected, but then in a blink of an eye it turns back to that preloaded one. I thought that .ClearSelection() will hepl, but it isn't (or maybe i use it in a wrong place). So i really wonder what to do and will really appreciate your help
One of the most important things you need to know about ASP.NET is the page life-cycle. There is plenty of help on the internet for this. Here is a quick link: http://blogs.msdn.com/b/aspnetue/archive/2010/01/14/asp-net-page-life-cycle-diagram.aspx.
Notice that the Page_Load event is fire before any event handling. This means that if you are using an event handler to catch changes in the dropdown your current code will reset it to the query string value first.
Of course that is a very big problem so ASP.NET has added a Page.IsPostBack property to help. This will be true only one the first load of the page and false for all event handling postbacks. Using this information you can tweak your routine to only apply the value when IsPostBack is false.
if (!Page.IsPostBack)
{
string strStatus = Request.QueryString["status"];
DListStatus.SelectedValue = strStatus;
}
Check if is it is a post back
if (!Page.IsPostBack)
{
string strStatus = Request.QueryString["status"];
DListStatus.SelectedValue = strStatus;
}
When you select a new item, does it invoke a post-back to the server? Possibly for a SelectedIndexChanged event?
If so, you're clobbering the selected value on each post-back. Page_Load gets invoked a lot. Any time the page does anything server-side, basically. It's part of the page lifecycle for everything the page does. So every event on the page (button click, selected index changed, etc.) is going to run the code in Page_Load before it runs any event handler code.
To avoid clobbering this value, you can wrap this code in a conditional to check if this is an initial page load vs. a triggered post-back:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
string strStatus = Request.QueryString["status"];
DListStatus.SelectedValue = strStatus;
}
}

textbox does not accept a value in asp.net

This code a have written for an asp.net website, v2005
System.Web.UI.WebControls.TextBox txtEFName = new System.Web.UI.WebControls.TextBox();
phFname.Controls.Add(txtEFName);
placeHolder1.Controls.Add(TextBox1);
This code when executed, always shows the value of the textbox "" even if I enter some string.
Please help.
Dynamic controls need to be re-created each time the page loads. So you need to have that code execute during the Page_Init event. Note: You need to assign a unique ID for this control that stays the same each time the page loads.
Why all this?
Because the control is not contained in the markup (the .aspx file), you need to add it again every time the page loads. So how does it retain its value? The value will be stored in the ViewState, and as long as the control has the same ID it will be repopulated with the correct value.
To keep things running smoothly, let's put the code for adding the control in a separate function.
Private void AddMyControl()
{
System.Web.UI.WebControls.TextBox txtEFName = new System.Web.UI.WebControls.TextBox();
txtEFName.ID = something unique;
phFname.Controls.Add(txtEFName);
}
So we can call it from both the click handler and the Page_Init handler, but we only need to call it in the Page_Init if we have already clicked. So let's store that as a flag inside a Session variable (you can also store it in the ViewState if you like, but let's keep it that way for now). So our click handler will now look something like this:
void ButtonSomething_Click(Object Sender, EventArgs e)
{
AddMyControl();
Session["MyControlFlag"] == true;
}
Now we need our Page_Init handler:
Public void Page_Init(Object Sender, EventArgs e)
{
if(Session["MyControlFlag"]!=null && (bool)Session["MyControlFlag"])
AddMyControl();
}

How do i get selected radiobuttonlist in asp.net?

I am using following code for a radiobuttonlist with default value of yes.
<asp:RadioButtonList ID="RadioButtonList1" runat="server" onselectedindexchanged="radiobtnlist_SelectedIndexChanged">
<asp:ListItem Selected="True">YES</asp:ListItem>
<asp:ListItem>NO</asp:ListItem>
</asp:RadioButtonList>
Every time when the value of the radiobtnlist is changed an event is fired.I am using following c# code for selected index changed
protected void radiobtnlist_SelectedIndexChanged(object sender, EventArgs e)
{
//do work
}
Problem is that when radiobtnlist value is set as No and the selection is not changed but the selectedindex change event is fired and when radiobtnlist is set as Yes, the selectedindex change event is not fired.
I have to find the selection of radiobtnlist everytime before postback and if its value is changed then saved data in db but how to find the selected value of radiobtnlist with a default value on a ListItem.
I think I get what you are saying.
The default answer is YES so this means that when a user wants YES to be selected, it is already selected hence they leave it alone. Because the RadioList value is left alone, no events are triggered.
Based on the code you provided I can see there is no "AutoPostBack" set. If this is the case, then I am assuming that you are triggering a postback via a submit button.
If you are triggering a postback via a submit button then you could put your logic in there. That way it will be triggered every time. E.g.:
protected void submit_click(object sender, EventArgs e)
{
var answerIsYes = (radiobtnlist.SelectedIndex == 0);
//store value to DB
}
You didn't specify if your form is going to be used for editing existing data. If it is, then it won't be efficient to be storing the value of the RadioList back to the database every postback. You need to consider how you will change it so that it only stores the value if the value CHANGES.

Executing last action when back button pressed ASP.Net

I have a ListBox with a "list of servers" that has AutoPostBack enabled and an SelectedIndexChanged event attached to it:
protected void lbServerList_SelectedIndexChanged(object sender, EventArgs e)
{
if ( lbServerList.SelectedValue.ToString() != "")
{
Response.Redirect("detail.aspx?Server=" + lbServerList.SelectedValue.ToString());
}
}
Then I have a textbox to add a "server" with a button "btnServertoAdd" (to execute the addition)
protected void btnServertoAdd_Click(object sender, EventArgs e)
{
Response.Redirect("add.aspx?Server=" + tbServertoAdd.Text);
}
Scenario: If I select an item from the ListBox it will go to detail.aspx showing the server specs: Awesome.
Now, If I click back (browser button) and then type something in the TextBox and click btnServerToAdd it will still go to detail.aspx and not to add.aspx as it should....
How can I fix this?
Let me know if more code is needed.
This is occurring because when you click the button, the selected server is also different from the original value (as stored in the view state). Both events are fired, but evidently the SelectedIndexChanged event is fired first and the Redirect skips the rest of the processing.
I can't think of how to not make the SelectedIndexChanged event fire the second time around, so instead what you could do is, instead of Redirecting in the events themselves:
Have a pair of bool member variables in your page class.
Set one to true in each event handler.
In the page OnLoadComplete event, check each and redirect as necessary:
If both are true, redirect to add.aspx.
If one is true, redirect to the corresponding page.
Otherwise don't redirect at all.

Categories