DropDownList AutoPostBack not hitting break point - asp.net

The auto post back for my drop down list is not hitting the break point in the code behind. It appears that changing the value of the drop down list is not causing the post back at all.
<asp:DropDownList ID="RidingType" runat="server" CssClass="option" DataValueField="VarId" DataTextField="Name" AutoPostBack="true" OnSelectedIndexChanged="RidingType_SelectedIndexChanged"></asp:DropDownList>
I have tried both OnSelectedIndexChanged and OnTextChanged. I am doing something similar on a different page, where it does work as expected.
<asp:DropDownList CssClass="listBoxes" runat="server" ID="lstBrands" DataValueField="brand" DataTextField="brand" AutoPostBack="true" OnTextChanged="lstBrands_SelectedIndexChanged" Width="100%"></asp:DropDownList>
I've done everything I can to match up the surrounding environments. Any ideas as to why the first appears not to post back and the second works correctly?
Edit:
Here is an excerpt from the code behind the binding function
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack)
{
/* code to set up other drop down lists */
BindRidingType();
/* more of the same */
}
}
private void BindRidingType()
{
prams[3].Value = "Riding Type";
RidingType.DataSource = ReturnSelection(prams); //return DataTable from Database
RidingType.SelectedValue = DefaultValue("Riding Type"); //Finds default value for list
RidingType.DataBind();
}
Per suggestion I tried not setting a default value, but I saw no change.
Edit:
The event handler as requested
protected void RidingType_SelectedIndexChanged(object sender, EventArgs e)
{
throw new NotImplementedException();
}

Related

(ModalPopupExtender) two components with the same id can't be added to the application

I have a user control which I add on a page whenever user click on button. Following is the code to add control.
protected void Page_Init(object sender, EventArgs e)
{
if (Session["ControlCount"] != null)
{
for (int i = 1; i <= (int)Session["ControlCount"]; i++)
{
Control myUserControl = LoadControl("~/Controls/MessageControl.ascx");
divMessageControl.Controls.Add(myUserControl);
}
}
}
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnExpand_Click(object sender, EventArgs e)
{
int count = 0;
if (Session["ControlCount"] != null)
{
count = Convert.ToInt32(Session["ControlCount"]);
}
Control myUserControl = (Control)Page.LoadControl("~/Controls/MessageControl.ascx");
divMessageControl.Controls.Add(myUserControl);
Session["ControlCount"] = count + 1;
}
This control has ModalPopupExtender popup. When I add 2nd control on page it throws an error internally which i can see in firebug. How to make this popup id unique?
<asp:ModalPopupExtender ID="mpeReply" BehaviorID="mpeReply" runat="server" TargetControlID="btnReply"
PopupControlID="pnlReply" BackgroundCssClass="ModalPopupBG1">
</asp:ModalPopupExtender>
Sys.InvalidOperationException: Sys.InvalidOperationException: Two
components with the same id 'mpeReply' can't be added to the
application.
I have found the solution to this problem, as much as a lot of people have said, the simple solution is that your HTML is not properly formed - there is either an extra or missing closing tag to an element. Make sure that all your tags are properly closed and the problem should go away - struggled all day with this one!
I used this code to fix my problem, notice the ScriptMode is set to "Release"
<AjaxControlToolkit:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server" ScriptMode="Release">
</AjaxControlToolkit:ToolkitScriptManager>
I see a similar answer from this link:
http://www.advancesharp.com/questions/17658/sys-invalidoperationexception-two-components-with-the-same-id-xxx-can-t-be-added-to-the-application
Remove BehaviorID property from extender
Similar issue here. The solution for me was to change the Script Manager from a shortcut close tag to the full close tag , after adding the ScriptMode="Release" attribute:
Change:
<asp:ScriptManager ID="ScriptManager1" ScriptMode="Release" runat="server" />
to:
<asp:ScriptManager ID="ScriptManager1" ScriptMode="Release" runat="server></asp:ScriptManager>

Why ispostback not working with dropdown box

I want to keep selected item after page reload:
Excerpt from .aspx:
<asp:DropDownList ID="MyDropDown" runat="server" AutoPostBack="true"
onselectedindexchanged="MyDropDown_SelectedIndexChanged">
</asp:DropDownList>
Exerpt from .cs in page_load
if (!IsPostBack)
{
PopulateDropDownList();
}
with
private void PopulateDropDownList()
{
MyDropDown.Items.Add("1");
MyDropDown.Items.Add("2");
}
protected void MyDropDown_SelectedIndexChanged(object sender, EventArgs e)
{
Response.Redirect(Request.RawUrl);
}
Response.Redirect refresh the page and you will loose view state that will have selected index. You can put the selected index in session before redirecting.
protected void MyDropDown_SelectedIndexChanged(object sender, EventArgs e)
{
Session["MyDropDownSelectedIndex"] = MyDropDown.SelectedIndex.ToString();
Response.Redirect(Request.RawUrl);
}
You need to populate the drop down list in the Page init event. If you do that during Page load event the view state cannot be restored correctly (because the drop down list is not populated before Page load event) so the on selected index changed event cannot be fired.
EDIT: you may want to cache the data which populate the drop down list to save some around trip to the database. I think you do not need to redirect in the on selected index changed event too.

textbox.text always returning empty string instead of user's entered text

I am very surprised to see last night my code was working fine and the next day suddenly my textbox.text always have empty string..
My code is:
Name of Event* :
<br />
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<br />
Code behind:
protected void Page_Load(object sender, EventArgs e) {
}
protected void create_Click(object sender, EventArgs e) {
if (!object.Equals(Session["UserLoginId"], null)) {
int mid = 0;
int cid = 0;
bool valid = true;
if (this.TextBox1.Text == "") {
error.Text = "<p style='color:red'>Marked Fields are compulsory!!</p>";
}
else {
.... // database insert ....
}
I am always ending up with an error.text value.
Why?
Had a similar problem with text boxes getting cleared on adding a new row. It was the issue of the page reloading when the add button was clicked.
Fixed the issue by adding:
Sub Page_Load
If Not IsPostBack Then
BindGrid()
End If
End Sub
Per Microsoft's documentation http://msdn.microsoft.com/en-us/library/aa478966.aspx.
Kinda mentioned but you should make sure your checking your that Post_Back event is not clearing your textbox. It would by default.
Try something like this:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
if (this.TextBox1.Text == "")
{
error.Text = "<p style='color:red'>Marked Fields are compulsory!!</p>";
}
else
{
//.....
}
}
}
I had a similar problem. I had a textarea feeding data to a database on postback. I also designed the page to populate the textarea from the same database field. The reason it failed was because I forgot to put my reload logic inside an if(!IsPostPack) {} block. When a post back occurs the page load event gets fired again and my reload logic blanked the textarea before I could record the initial value.
If the page make a post back, then all the data , the user entered ,will be erased,as the controls are stateless, so u should keep your data entry through EnableViewState = true.
I am having this issue, but i'm using Telerik Ajax request with target in javascript. I have a RadTextBox and a RadButton. I call the same code from both of them but if i call it from the textBox and request a postback, the textbox is empty in the page load. So i call RadAjaxManager.ajaxRequestWithTarget('someUserControlClientID', 'myTextBoxText');
So in the page_load, i can grab the text, in case it's not sent to the server with the arguments sent, Request.Form("__EVENTARGUMENT") will hold my textBox value.
by the way, RadAjaxManager.ajaxRequestWithTarget is like __doPostBack('targetID', 'arguments');. Hope this helps someone. I don't have time to investigate why i lose the text with this request, so this is the workaround i did.

How to add persistent dynamic controls based on user input (not on initial page load)

I am familiar with creating and persisting dynamic controls on the first load of a page and on subsequent postbacks but I am having trouble with the following user initiated scenario...
In my demo I have a placeholder, two buttons and a literal
<div>
<asp:PlaceHolder ID="phResponses" runat="server" />
</div>
<div>
<asp:Button ID="btnAdd" Text="Add" runat="server" OnClick="Add"/>
<asp:Button ID="btnInspect" Text="Inspect" runat="server" OnClick="Inspect"/>
</div>
<div>
<asp:Literal ID="litResult" runat="server"/>
</div>
I want the user to be able to click the add button to provide a response so I have...
protected void Page_Init(object sender, EventArgs e)
{
BuildControls();
}
protected void Add(object sender, EventArgs e)
{
BuildControls();
}
protected void BuildControls()
{
phResponses.Controls.Add(new LiteralControl { ID = "response_" + _Count.ToString() });
_Count++;
}
_Count is a static member variable to enable me to have unique ids for the new controls. I realise I need to rebuild the dynamic controls on Page_Init but the problem is that I end up with 2 new Literal controls on every postback. Also if any Text property is put into the new controls it is lost when the controls are rebuilt.
So how do I avoid adding multiple controls and how do I persist newly added properties when rebuilding these controls?
I use the following to inspect the responses
protected void Inspect(object sender, EventArgs e)
{
foreach (var control in phResponses.Controls)
{
if (control is LiteralControl)
{
litResults.Text += "<p>" + control.Text + " : " + control.ID + "</p>";
}
}
}
Which itself adds another unwanted control because of the rebuilding on Page_Init
I'd not sure that I quite understand what you're asking, but it looks like you just want to ensure that BuildControls is only called once per lifecycle. You could do that by making the following changes:
Add a new private bool _isControlsBuilt = false;.
Change Page_Init to check _isControlsBuilt before calling BuildControls.
Set _isControlsBuilt to true within BuildControls.
Make sure that BuildControls occurs earlier in the page lifecycle than Page_Init.
As for losing the values of controls on postback, it'll be that they're never hitting the viewstate. I'm not sure if it'd work, but my first guess would be to add a line to the end of BuildControls to call Page.RegisterRequiresControlState:
protected void BuildControls()
{
LiteralControl newLiteral = new LiteralControl { ID = "response_" + _Count };
this.RegisterRequiresControlState(newLiteral);
phResponses.Controls.Add(newLiteral);
_Count++;
_isControlsBuilt = true;
}
If that doesn't work (which might imply that it's the _view_state, not the _control_state that matters to you here), you may need to look at rolling your own viewstate. I wrote about how to do that in my answer to #3854193, which you might find useful.

DotNetNuke ObjectDataSource.SelectMethod not being saved in viewstate

I'm using DotNetNuke 4.9.2 and am running into an odd issue.
I have a MultiView in the module that I'm developing, and in one of the views have a GridView that is bound to an ObjectDataSource.
In a separate view, i have several buttons that will switch the SelectMethod of the ObjectDataSource in the 2nd view and then set that view active. That all works fine, until the grid is sorted on the 2nd view - which causes a postback and the ODS somehow picks up its original SelectMethod. The SelectParameters that are assigned at the same time in the code-behind stick though.
Seems to me that the ObjectDataSource should be remembering the SelectMethod in viewstate, shouldn't it?
<asp:ObjectDataSource runat="server" ID="MyObjectDataSource" SelectMethod="MyFirstSelectMethod" TypeName="Whatever"></asp:ObjectDataSource>
protected void Button1_Click(object sender, EventArgs e)
{
MyObjectDataSource.SelectMethod = "MyNewMethod";
// more code here to change the parameters as well...
MyMultiView.SetActiveView(MyView2);
}
When I run that button click, the grid displays as expected. When I click on one of the column headers for the GridView and break in the page load to inspect the SelectMethod, it has reverted to the one declared in the markup.
Any suggestions as to what my problem could be here?
I'm guessing you've made sure that you're not resetting .SelectMethod when the page reloads?
I ended up working around the issue by just using a page property to hold the selectmethod, and then resetting it on each postback...
protected string MySelectMethod
{
get
{
return (string)ViewState["MySelectMethod"] ?? MySearchResultsDataSource.SelectMethod;
}
set
{
ViewState["MySelectMethod"] = value;
MySearchResultsDataSource.SelectMethod = value;
}
}
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
MySearchResultsDataSource.SelectMethod = MySelectMethod;
}
}
protected void MyButton_Click(object sender, EventArgs e)
{
MySelectMethod = "MyNewMethod";
}
Still not sure why that SelectMethod prop doesn't stick on a postback in nuke. I'm sure this has worked fine for me in straight asp.net projects in the past...

Resources