page strange behavior - c#

I face so strange action in my page.
I have a radio button list, according to the selection i execute specific code.
The problem is:
for example when i select option 2 then i select back option 1.
the page maintains the state(all the drop down lists maintain their previous selections) and i need to click the link one more time to force the page to enter this condition:
if (!Page.IsPostBack)
{
BindCamp(0);
BindCamp(1);
}
my aspx :
<asp:RadioButtonList ID="rbl" runat="server"
OnSelectedIndexChanged="rbl_SelectedIndexChanged"
RepeatDirection="Horizontal" Width="200px" AutoPostBack="True">
<asp:ListItem Value="0" Selected="True">view data</asp:ListItem>
<asp:ListItem Value="1">view report</asp:ListItem>
</asp:RadioButtonList>
My code:
protected void rbl_SelectedIndexChanged(object sender, EventArgs e)
{
if (rbl.SelectedItem.Value == "0")
{
pnl_view.Visible = true;
pnl_stat.Visible = false;
pnl_rep.Visible = false;
}
else
{
pnl_view.Visible = false;
pnl_all.Visible = false;
pnl_Dean.Visible = false;
pnl_research.Visible = false;
pnl_stat.Visible = true;
}
}

Per your comments, DLL's will always retain their values unless you manually set the selection, you set EnableViewState="false" (which disabled all viewstate then). So I think you may need code that does:
ddl.SelectedIndex = 0; // or -1 depending on whether you want an item selected
Upon clicking the next radio button.

Related

dropdown selected item and repose.redirect

I have two dropdownlist in my project and get the items from sql server. One of them show list of something (And I named it DropdownSoore) and another one show list of members of it (And I named it DropdownAye) that update when select an item from DropdownSoore. then when select an item from DropdownAye go to page of them by forwarding query string. I have no problem to updating DropdownAye but when I select item from it and redirect to page of it, the DropdownAye lose the selected item and show the first item (as default) and index to query string in url.
what should I do?
Excuse me about my grammer, I'm not English...
I set DropdownSoore:
<asp:DropDownList ID="DropDownListSoore" runat="server" class="nav-link btn btn-outline-secondary dropdown-toggle" aria-haspopup="true" aria-expanded="true" AutoPostBack="True"></asp:DropDownList>
for (int i = 0; i <= dt.Rows.Count - 1; i++)
{
string IdSoore = Convert.ToString(dt.Rows[i]["IdSoore"]);
string NameSoore = Convert.ToString(dt.Rows[i]["NameSoore"]);
DropDownListSoore.Items.Add(IdSoore + "." + NameSoore);
}
string forwardedIdSoore = Request.QueryString["IdSoore"];
if (forwardedIdSoore != null)
{
DropDownListSoore.Items.FindByValue(forwardedIdSoore);
}
And then set DropdownAye:
<asp:DropDownList ID="DropDownListAye" runat="server" class="nav-link btn btn-outline-secondary dropdown-toggle" aria-haspopup="true" aria-expanded="true" OnSelectedIndexChanged="DropDownListAye_SelectedIndexChanged" AutoPostBack="True"></asp:DropDownList>
DropDownListAye.Items.Clear();
for (int i = 0; i <= dt1.Rows.Count - 1; i++)
{
DropDownListAye.Items.Add(Convert.ToString(dt1.Rows[i]["NumberAye"]));
}
int iSelectedAye = Convert.ToInt32(DropDownListAye.SelectedIndex) + 1;
string SelectedAye = Convert.ToString(dt1.Rows[iSelectedAye]["IdAye"]);
Session["SSelectedAye"] = SelectedAye;
string forwardedIdAye = Request.QueryString["IdAye"];
if (forwardedIdSoore != null)
{
DropDownListSoore.Items.FindByValue(forwardedIdAye);
}
in page_Load. and dont have problem to update DopdownAye but when I used it to redirect always get IdAye=1 in url and show the first item of DropdownAye ...:
protected void DropDownListAye_SelectedIndexChanged(object sender, EventArgs e)
{
int SelectedAye = Convert.ToInt32(Session["SSelectedAye"]);
int SelectedSoore = Convert.ToInt32(DropDownListSoore.SelectedIndex) + 1;
string forward = "~/contentAye.aspx?IdSoore=" + SelectedSoore + "&IdAye=" + SelectedAye;
Response.Redirect(forward);
}
I try !IsPostBack but dont have utility too.
I do all thing I think and i dont know what shoild i do.
And where are you loading up these infomration?
Remember, page load ALWAYS fires and triggers for each post-back, for each button click, and any OTHER event on the page that calls code behind.
What does the above really mean?
Well, it means that you need to ONLY ONE TIME load up the drop downs, the gridview(s), or whatever else you have.
So, for the last 200+ web pages I have built, I ALWAYS have this code stub in the page load event:
so this markup:
<h3>Select Hotel</h3>
<asp:DropDownList ID="DropDownList1" runat="server"
DataValueField="ID"
DataTextField="HotelName" Width="356px">
</asp:DropDownList>
<br />
<br />
<asp:Button ID="Button1" runat="server"
Text="Show/get/display drop selection" OnClick="Button1_Click"
CssClass="btn" />
<br />
<h3>Selected result</h3>
<asp:Label ID="Label1" runat="server" Text=""></asp:Label>
and code behind:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
// load up data, controls etc.
string strSQL =
"SELECT ID, HotelName FROM tblHotelsA ORDER BY HotelName";
DataTable dt = General.MyRst(strSQL);
DropDownList1.DataSource = dt;
DropDownList1.DataBind();
DropDownList1.Items.Insert(0, new ListItem("Please Select Hotel", ""));
}
}
protected void Button1_Click(object sender, EventArgs e)
{
string sResault =
$#"dropdown list value (pkid) = {DropDownList1.SelectedItem.Value}
<br/>
Dropdown list Text (Hotel) = {DropDownList1.SelectedItem.Text}";
Label1.Text = sResault;
}
and the result:
SUPER important:
If I leave out the !IsPostBack test in page load, then for EVERY button click, the dropdown list re-load code will trigger, and runs BEFORE your button stubb, or post back. As a result, I will see/find/get no valid value from the drop down list, since page load ALWAYS runs before the given code stub, and thus if page load "every time" re-loads the data, then it will blow out the choosen value in the drop down list.
So, loading up of grids, data, dropdowns etc. can ONLY occur one time in page load, since page load ALWAYS runs before each button or event code stub you have behind.
If you thus only load up the controls and dropdowns on the first REAL page load, then the values the user selects in those dropdowns should work, but only will work if you ALWAYS include that all important if (!IsPostBack) code stub in your page load event.
Now, of course in place of that button to loadup + display the dropdown list into that label?
Well, of course that button click may well (like often) jump or navigate to another page. So, in place of that code to fill out the selected value(s) into that lable, we could pass the selected value to the next page. And how to do that? Well, you can use session(), you can use parmaters in the URL, or you can even use a post-back URL, and then the WHOLE previous page becomes available (Page.Previous), which then in theory allows you to grab ANY and ALL values from the previous page.
but, say we choose session() to pass the value, then this:
Session["HotelPK"] = DropDownList1.SelectedItem.Value;
Response.Redirect("GridFun3.aspx");

Dropdownlist how to save selected value to ViewState?

Dropdownlist how to save selected value to ViewState ?
I have a dropdownlist that when changed will save the new value into a ViewState variable, so that after a postback, the dropdownlist will retrieve it's selected value from ViewState if previously set.
But I can't store the selected value in DropDownList1_SelectedIndexChanged to ViewState because when reload page (after update database with sql query update) in DropDownList I don't have any selected value.
Can you please help me figure out the problem?
Thanks in advance.
My code below.
<asp:DropDownList ID="ddl1" runat="server" AutoPostBack="true"
OnSelectedIndexChanged="ddl1_SelectedIndexChanged"
EnableViewState="true" ViewStateMode="Enabled">
<asp:ListItem Value="" Text="[Selected]"></asp:ListItem>
<asp:ListItem Value="" Text="------"></asp:ListItem>
<asp:ListItem Value="1" Text="A"> </asp:ListItem>
<asp:ListItem Value="2" Text="B"> </asp:ListItem>
<asp:ListItem Value="3" Text="C"> </asp:ListItem>
<asp:ListItem Value="4" Text="D"> </asp:ListItem>
<asp:ListItem Value="" Text="------"></asp:ListItem>
</asp:DropDownList>
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
BindData();
if (ViewState["List1_Value"] != null)
{
ddl1.SelectedValue = ViewState["List1_Value"].ToString();
}
}
}
protected void ddl1_SelectedIndexChanged(object sender, EventArgs e)
{
BindData();
ViewState["List1_Value"] = ddl1.SelectedValue.ToString();
}
private void SqlUpdate()
{
sql = String.Format(#" UPDATE ..... ";
using (OdbcConnection cn =
new OdbcConnection(ConfigurationManager.ConnectionStrings["cn"].ConnectionString))
{
using (OdbcCommand cmd = new OdbcCommand(sql, cn))
{
cmd.Connection.Open();
cmd.ExecuteNonQuery();
Page.ClientScript.RegisterStartupScript(this.GetType(), "Msg", "alert('Ok.');window.location='default.aspx';", true);
}
}
}
You have AutoPostBack enabled, so every time the selection change it posts back to your Page_Load. You are only filling out the value when it is not a postback, so this will never occur.
Try moving the code to set the value outside of the if (!Page.IsPostBack) block. Maybe something like so:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
BindData();
}
if (ViewState["List1_Value"] != null)
{
ddl1.SelectedValue = ViewState["List1_Value"].ToString();
}
}
when reload page (after update database with sql query update) in DropDownList I don't have any selected value
Presumably you're "reloading" in one of two ways:
1. Causing a Post-Back
This won't work in your case because you're not using the value in a post-back:
if (!Page.IsPostBack)
{
BindData();
if (ViewState["List1_Value"] != null)
{
ddl1.SelectedValue = ViewState["List1_Value"].ToString();
}
}
If you want to bind the selected value in a post-back then you need to move that code outside of that conditional:
if (!Page.IsPostBack)
{
BindData();
}
if (ViewState["List1_Value"] != null)
{
ddl1.SelectedValue = ViewState["List1_Value"].ToString();
}
2. Making a New Request
If you're manually "reloading" the page by simply re-requesting the page from the browser's address bar, then the ViewState is going to be empty. ViewState is part of the form values in a POST request, but loading a page from the address bar issues a GET request with no values. So the ViewState will be empty.
Remove BindData() from your SelectedIndexChanged method:
protected void ddl1_SelectedIndexChanged(object sender, EventArgs e)
{
ViewState["List1_Value"] = ddl1.SelectedValue.ToString();
}
And as others have mentioned, you attempt to set ddl1.SelectedValue inside a condition that only runs in NOT postback, which means it will never capture the selected value on postback. So you will also want to address that by moving it outside the !Page.IsPostBack condition.
What you're doing is a postback from Javascript, in this case the ViewState is deleted as it is as if it were a new request.
In this case the only thing is to store it in session or send as a parameter to the page.
At last after update database simply binding a GridView it's easy !:
cmd.Connection.Open();
cmd.ExecuteNonQuery();
Page.ClientScript.RegisterStartupScript(this.GetType(), "Msg", "alert('Ok.');", true);
BindData();

Is it possible to programmatically input values in TextBox control before UpdateCommand runs

(C# asp.net 3.5) I have successfully pre-populated CheckBoxList3 in RowDataBound event. In edit mode, user may then make other checkbox selections. I have successfully captured the new values, creating a new comma-delimited string that updates SQL in _RowUpdating event after Update link is clicked. The problem is my update is being overriden by the GridView1s update. *The new string is not physically input by user in the TextBox2 control.
It seems I have two choices:
Pass the comma-delimited string built from checkboxlist3 selections
to TextBox2 control programmatically before UpdateCommand is run. P*Is this possible?* I've
googled everywhere with no clearcut solutions. I've also tried this code in RowUpdating and it makes to difference:
TextBox tb2 = (TextBox)GridView1.Rows[e.RowIndex].Cells[1].FindControl("TextBox2");
tb2.Text = strCheckBoxList3.Substring(0, strCheckBoxList3.Length - 2);
Update sql manually like I'm doing only place Sql call AFTER the "natural" update (for lack of
better words). If this is an option, what method to run the update in because placing it in RowUpdating always gets reversed.
HTML:
<asp:TemplateField HeaderText="Endorsements" SortExpression="Endorsements">
<ItemTemplate>
<asp:Label ID="Label2" runat="server" Text='<%# Bind("Endorsements") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="TextBox2" runat="server" Text='<%# Bind("Endorsements") %>'></asp:TextBox>
<asp:CheckBoxList ID="CheckBoxList3" runat="server" Font-Size="Small" RepeatDirection="Horizontal" onselectedindexchanged="CheckBoxList3_SelectedIndexChanged"
AutoPostBack="True" >
<asp:ListItem Value="H">H</asp:ListItem>
<asp:ListItem Value="I">I</asp:ListItem>
<asp:ListItem Value="K">K</asp:ListItem>
<asp:ListItem Value="N">N</asp:ListItem>
<asp:ListItem Value="T">T</asp:ListItem>
<asp:ListItem Value="X">X</asp:ListItem>
</asp:CheckBoxList>
</EditItemTemplate>
</asp:TemplateField>
C#
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
//endorsements string
string strCheckBoxList3 = String.Empty;
//find endorsements checkboxlist in gridview.
CheckBoxList cbl3 = (CheckBoxList)GridView1.Rows[e.RowIndex].Cells[1].FindControl("CheckBoxList3");
try
{
// Build Endorsements string
if (cbl3 != null)
{
// determine which checkboxes have been checked
foreach (ListItem item in cbl3.Items)
{
// is item checked?
if (item.Selected == true)
{
// build string
strCheckBoxList3 += (item.Value + ", ");
}//end of if
}// end of foreach
// Save the value in ViewState object before the PostBack
ViewState["vsEndorsementsString"] = strCheckBoxList3;
}// end of if
}// end of endorsements try
catch (ArgumentOutOfRangeException ez)
{
System.Diagnostics.Debug.WriteLine(ez.Message + "; " + ez.Source + "; " + ez.TargetSite);
}
//Note: routine to update SQL was removed here
}
// New: pass strings to sql Update Command Parameters for two checkboxlist columns in gridview
protected void sdsMySqlDataSource_Updating(object sender, SqlDataSourceCommandEventArgs e)
{
string getViewStateEndorsementsString = ViewState["vsEndorsementsString"].ToString();
string getViewStateRestrictionsString = ViewState["vsRestrictionsString"].ToString();
foreach (System.Data.Common.DbParameter p in e.Command.Parameters)
{
if (p.ParameterName == "#Endorsements" && p.Value != null)
{
//Assign #Endorsements parameter
e.Command.Parameters["#Endorsements"].Value = getViewStateEndorsementsString.ToString();
}//if
if (p.ParameterName == "#Restrictions" && p.Value != null)
{
//Assign #Restrictions parameter
e.Command.Parameters["#Restrictions"].Value = getViewStateRestrictionsString.ToString();
}//if
}
}
The solution is to pass new values to Update Command Parameters in SqlDataSource _Updating event. Relevent updated code provided above.
I removed the SQL update routine that I had in _RowUpdating event entirely - it isn't needed. Then I saved the newly created comma-delimited string to ViewState object which I retrieve in SqlDataSource _Updating event.
Credit for me coming to this conclusion goes to leoinlios because of his post here: changing textbox value in code behind does not post back new value Plus I did a lot of reading about View State and found this to be the most useful article: TRULY Understanding ViewState

formview with ajax modal popup extender

I have tried this several ways and none of them seem to work for me. I have a formview and when the user goes into the edit mode and then clicks update I want a modal popup to show so they can type a note as to what they changed.
Here is my code
<ajaxToolkit:ModalPopupExtender ID="SubmitButton_ModalPopupExtender"
runat="server" OkControlID="EditNoteButton" PopupControlID="EditNotePanel"
BehaviorID="MPE" BackgroundCssClass="modalBackground"
TargetControlID="DummyButton">
</ajaxToolkit:ModalPopupExtender>
<asp:Panel ID="EditNotePanel" runat="server" CssClass="style105" Height="23px" style="display: none">
<asp:TextBox ID="EditNoteBox" runat="server" CssClass="style106" Height="68px" Width="223px">What Did You Change?</asp:TextBox> <br />
<asp:Button ID="EditNoteButton" runat="server" CssClass="style107" Height="29px" Text="Ok" Width="52px" CommandName="update" /> <br />
</asp:Panel>
C#
protected void ClientInformationForm_ItemCommand(Object sender, FormViewCommandEventArgs e)
{
//case statements
if (ClientInformationForm.CurrentMode == FormViewMode.Edit)
{
SubmitButton_ModalPopupExtender.TargetControlID = ((Button)ClientInformationForm.FindControl("SubmitButton")).UniqueID;
}
From what I have read that should work. I have tried showing it through javascript on clientclick. I have tried displaying it by calling modal.show() in the itemcommand but none of them are displaying it. Does it matter if the panel or popup are inside or outside the formview?
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack && Session["CurrentAccountId"] != null)
{
AddressTypeddl.DataBind();
ShippingAddressddl.DataBind();
AddressForm.DataBind();
}
if (ClientInformationForm.DataItemCount == 0)
{
ClientInformationForm.BackColor = Color.FromArgb(0xd9e2bf);
}
else
{
ClientInformationForm.BackColor = Color.White;
}
if (Session["CurrentAccountId"] == null)
{
NoteBox.Visible = false;
NewNoteButton.Visible = false;
NoteTypeddl.Visible = false;
NoteLabel.Visible = false;
NoteTypeLabel.Visible = false;
NewNoteLabel.Visible = false;
CreditCardView.Visible = false;
NewAccountButton.Visible = true;
AddressTypeddl.Visible = false;
AddressLabel.Visible = false;
AddressForm.Visible = false;
}
else
{
NoteBox.Visible = true;
NewNoteButton.Visible = true;
NoteTypeddl.Visible = true;
NoteLabel.Visible = true;
NoteTypeLabel.Visible = true;
NewNoteLabel.Visible = true;
CreditCardView.Visible = true;
NewAccountButton.Visible = false;
AddressTypeddl.Visible = true;
AddressLabel.Visible = true;
AddressForm.Visible = true;
}
}
So I just realized if I want people to keep posting I need to edit my original post and not just add a note, so hopefully this helps. Anyway, I still can't get this to work and I don't know what is causing my popup not to fire?
If you want to pop up the modal after the user makes their edits, I wouldn't use the ItemCommand event.
I haven't used FormViews much, mostly GridViews. But I'm assuming that the principles are mostly the same.
Have you tried showing the modal in the ItemUpdated event?
http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.formview.itemupdated(v=vs.110).aspx
I haven't tried this before, but I'd like to think that something like this may work:
protected void ClientInformationForm_ItemUpdated(Object sender, FormViewUpdatedEventArgs e)
{
//capture ID of the updated record, and perhaps store it in a HiddenField that's in the modal
SubmitButton_ModalPopupExtender.Show();
}
Well after many days of trail and error I finally found out why this wasn't working. It came down to the dummy button. I was setting visible to false to hide the button and for some reason that doesn't work. Once I changed it to style= display:none; it fired fine. Weird that there was no error thrown it was just never popping up.

radio button list event not firing all the time

I have a very strange issue with a radio button list where it works fine but after a few clicks it doesn't seem to fire the SelectedIndexChanged event and just remains on the same value after postback.
<asp:RadioButtonList runat="server" ID="rblShowRecords" AutoPostBack="true"
OnSelectedIndexChanged="rblShowRecords_SelectedIndexChanged" RepeatDirection="Horizontal">
<asp:ListItem >Show Active/Completed</asp:ListItem>
<asp:ListItem >Show Active</asp:ListItem>
<asp:ListItem >Show Completed</asp:ListItem>
</asp:RadioButtonList>
Here is the event method:
protected void rblShowRecords_SelectedIndexChanged(object sender, EventArgs e)
{
switch (rblShowRecords.SelectedItem.Text)
{
case "Show Active/Completed":
CEDatabaseSource.SelectCommand = ConfigurationManager.AppSettings["SelectAllRecords"].ToString();//"SELECT * FROM [CERecord] ORDER BY [Priority]";
break;
case "Show Active":
CEDatabaseSource.SelectCommand = ConfigurationManager.AppSettings["SelectActiveRecords"].ToString();
break;
case "Show Completed":
CEDatabaseSource.SelectCommand = ConfigurationManager.AppSettings["SelectCompletedRecords"].ToString();
break;
default:
break;
}
CEDatabaseSource.DataBind(); //Commit the changes to the data source.
gvRecordList.DataBind(); //Update the GridView
rblShowRecords.SelectedItem.Value = CEDatabaseSource.SelectCommand; //Update the value of the selected radio button with the selected SELECT command.
}
I don't understand why it only works precisely 3 times but after, it never enters the method above.
Trying the same thing but with a dropdownlist, also works 3 times and then this error:
Invalid postback or callback argument. Event validation is enabled using <pages enableEventValidation="true"/> in configuration or <%# Page EnableEventValidation="true" %> in a page. For security purposes, this feature verifies that arguments to postback or callback events originate from the server control that originally rendered them. If the data is valid and expected, use the ClientScriptManager.RegisterForEventValidation method in order to register the postback or callback data for validation
Based on your last comment, remove your code that sets SQL queries to SelectedItem.Value and use SelectedItem.Text property to get command when you need it, select queries may contain characters like > , <, etc that will cause invalid postback error, you can change your code to following:
string GetCommand()
{
switch (rblShowRecords.SelectedItem.Text)
{
case "Show Active/Completed":
return ConfigurationManager.AppSettings["SelectAllRecords"].ToString();
case "Show Active":
return ConfigurationManager.AppSettings["SelectActiveRecords"].ToString();
case "Show Completed":
return ConfigurationManager.AppSettings["SelectCompletedRecords"].ToString();
default:
return "";
}
}
In Page_Load
if (IsPostBack)
{
CEDatabaseSource.SelectCommand = GetCommand();
CEDatabaseSource.DataBind();
}
Now your SelectedIndexChanged code will be
protected void rblShowRecords_SelectedIndexChanged(object sender, EventArgs e)
{
CEDatabaseSource.SelectCommand = GetCommand();
CEDatabaseSource.DataBind(); //Commit the changes to the data source.
gvRecordList.DataBind(); //Update the GridView
}

Categories

Resources