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.
Related
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;
}
I have a DropDownList in my page:
<asp:DropDownList ID="ddlPra" ClientIDMode="Static" CssClass="chosen-select" runat="server" OnSelectedIndexChanged="Practice_SelectedIndexChanged"></asp:DropDownList>
Code Behind:
protected void Practice_SelectedIndexChanged(object sender, EventArgs e)
{
MessageBox.Show(ddlCli.SelectedItem.Text);
}
I also have an UpdatePanel which has a GridView that displays some data with links. The issue I am having is when the page loads and I change the option from the select drop down, I don't get an alert but when I click on anything inside theUpdatePanel` the alert is displayed.
How do I fix it so that the DropDownList works independent from the UpdatePanel
Why DropDownList event fires after another event?
Because you have not set AutoPostBack="true", it is false by default. That means that it will not post back immediately after the user selected another item. But the event will be triggered on the next postback anyway, independent of the control that caused it.
I have a GridView to which I've using an ObjectDataSoure as the data source. The ObjectDataSource is taking in parameters from a TextBox and DropDownList which is then passed into the stored procedure. There is also a button called Search which can be used to force a refresh on the GridView by providing/changing values in the TextBox and/or DropDownList. However I noticed that if I changed the values I don't have to click on the Search button; simply clicking on the GridView causes a data bind.
Is there anyway to prevent this action while still using the ObjectDataSource?
When you assign a DataSourceID on the GridView, the grid will automatically bind to the ObjectDataSource. You can simply omit that property on the GridView and wait until the Search button's click event to assign it.
The problem is that every time any parameter used for ObjectDataSource is changed the ODS performs a "DataBind".
You can use two HiddenFields to keep the values. The ObjectDataSource will only do a "DataBind" when you change the values on the HiddenFields. So you can change the values on the TextBox and DropDownList, and when you want a "DataBind" you only need to copy the values to the HiddenFields.
Here is a code sample I made for another question: Q11874496WebApp.7z
In my case i just used a private boolean field in codebehind and respect its values on datasourceName_Selecting event.
For example i declared the following:
private bool IsInSearchingMode = false;
set it true only in search mode:
protected void btnSearch_Click(object sender, EventArgs e)
{
this.IsInSearchingMode = true;
this.gridData.DataBind();
}
and then check the value on Selecting event:
protected void myLinqDataSource_Selecting(object sender, LinqDataSourceSelectEventArgs e)
{
e.Result = new List<BranchDataClass>();
if (!this.IsInSearchingMode)
return;
// e.result = select code
}
A drawback is that a new page_load that is not caused by btnSearch_Click will reset the private variable's value. If you want it to be persistent you should use a hidden field as proposed or save it to viewstate.
I have a windows forms app in C#. Platform is vS 2005.
Following is the piece of code:
namespace HostApp
{
public partial class Form1 : Form
{
private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
{
comboBox2.Items.Add("Apples");
comboBox2.Items.Add("Oranges");
comboBox2.Items.Add("Grapefruits");
}
}
}
I run the app but the fruit names do not show up in the drop down of comboBox2. I am sure I am missing some line of code to "populate" the drop down with the entered values.
Any help would be much appreciated.
Thanks,
Viren
You add the items in the handler for the SelectedIndexChanged event. You need to move the code to InitializeComponent or another appropriate place.
Please check the following things:
You have added AutoPostBack="true" in the combo-box so that the selectedChange event is fired and post back happens.
Make sure you have nothung in ur Page load which refreshed the combo box. You can use IsPostBack to acheive loading of the values.
Your items are being added when the selected item is changed, but as there are no existing items this will never happen. Move those lines to the constructor for Form1 and it'll work.
The code you provided will only add items to comboBox2 when the selection changes in the control that is hooked up to comboBox2_SelectedIndexChanged.
There are two concepts at play here: Control Initialization/Databinding, and event handling.
The code you have written essentially says "If somebody selects something new in the combo box, add these 3 options to the combo box". That would happen every time the selected index changes in the combo box. This, of course, assumes you have even hooked up this event handler to the combo box to begin with. This is event handling.
What you are probably trying to do is initialize the control. This happens when you load the page and want to setup the initial options available in your page controls. Using the Init or Load event is probably where you want to setup the choices in your control. This is also when you would initialize your event handlers to say "When something happens, do this".
Move the code to the Page_Load event ...
The SelectedIndexChanged only fires when the ComboBox index has changed AND AutoPostBack = True.
EDIT: Sorry, it's a Form, I was thinking web ... move to Form_Load
For people having difficulties with autopostback and viewstate, beware of the page_load event.
If have been getting on this page alot when trying to google, so that's the reason i'll post it here.
If you fill your dropdownlist (or any other control) in the page_load method, be sure to write an extra control is there is a postback (triggered when changing value of a dropdownlist).
If you don't make that control, your controls will be refilled.
That mistake took me a while to figure out.
So what i'm saying is
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
//fill your controls here
}
}
Okay, I have a FormView with a couple of child controls in an InsertItemTemplate. One of them is a DropDownList, called DdlAssigned. I reference it in the Page's OnLoad method like so:
protected void Page_Load(object sender, EventArgs e)
{
((DropDownList)FrmAdd.FindControl("DdlAssigned")).SelectedValue =
((Guid)Membership.GetUser().ProviderUserKey).ToString();
}
Basically I'm just setting the default value of the DropDownList to the user currently logged in.
Anyway, when the page finishes loading the SelectedValue change isn't reflected on the page. I stepped through OnLoad and I can see the change reflected in my Watch list, but when all is said and done nothing's different on the page.
I figured it out. I'm still missing exactly why it doesn't work just on FormLoad, but performing the change in the FormView's DataBound event does the trick.
protected void FrmAdd_DataBound(object sender, EventArgs e)
{
// This is the same code as before, but done in the FormView's DataBound event.
((DropDownList)FrmAdd.Row.FindControl("DdlAssigned")).SelectedValue =
((Guid)Membership.GetUser().ProviderUserKey).ToString();
}
So, I guess the general rule of thumb is that if you are having problems making changes to controls when working with databinding, try to make them immediately after it has been bound.
I had a problem with dropdownlists and making the first value say something like, "Please select a value..." but without making it an actual selectable item, nor show up on the dropdownlist. I was binding the ddl in the page_load and I have to make sure that I set the text of the dropdownlist, AFTER it's been bound with data. You've accomplished the same thing by adding it to your databound section.