I am filling DDL dynamically :
<asp:DropDownList ID="ddlTimeZone" Style="width: auto" runat="server" >
</asp:DropDownList>
With this function :
private void initTimeZone()
{
var timeZones = TimeZoneInfo.GetSystemTimeZones();
foreach (TimeZoneInfo timeZone in timeZones)
{
ListItem item = new ListItem()
{
Text = timeZone.DisplayName,
Value = timeZone.Id
};
ddlTimeZone.Items.Add(item);
}
}
Everything works fine but when I try to get the selected value I get an empty string
string item = ddlTimeZone.SelectedValue; -> empty string..
How can i solve this problem?
Because of the life cycle of controls in ASP.NET building a dynamic values will "disappear" in the PostBack process.
Try to call your initTimeZone method outside the if(!IsPostBack) condition and see if it works. like this:
protected void Page_Load(object sender,EventArgs e) {
if(!Page.IsPostBack) {
//Some Code
}
initTimeZone();
}
Check Control.EnableViewState for page or parent control. Maybe you turn it off?
Related
I have a Web Form dependent on a Master Page, that contains a simple Form like this:
<asp:TextBox runat="server" ID="txtValue"></asp:TextBox>
<asp:DropDownList runat="server" ID="ddlProduct" />
<asp:Button runat="server" ID="btnConfirm" Text="Confirm" OnClick="btnConfirm_OnClick" />
on Page_Load I dynamically populate the DropDownList with values:
foreach(var product in products)
{
ListItem item = new ListItem(product.Nazev, product.ProductId.ToString());
ddlProduct.Items.Add(item);
}
Now .. normally if the DropDownList was populated statically, I would go with this, to get my selected value out of it:
protected void btnConfirm_OnClick(object sender, EventArgs e)
{
string selectedProduct = ddlProduct.SelectedValue;
}
But this is a no-go in this situation. Hence I try to directly get the selected value from POSTed parameters with one of those approaches (which are in fact practically the same):
protected void btnConfirm_OnClick(object sender, EventArgs e)
{
string selectedProduct = Request.Form.Get(ddlProdukt.ClientID);
string selectedProduct2 = Request.Params[ddlProdukt.ClientID];
}
But it doesn't work. If I debug it, the actual "id/name" of the DropDownList in the POSTed Form (Request.Params) is:
"ctl00$MainContent$ddlProdukt"
whereas the ClientId my approach gives me is:
"ctl00_MainContent_ddlProdukt"
I can't figure out, why does it replace '_' for '$' in the ID of my DDL control.. It seems to be such a trivial thing. There should be a better way to find out the right ID, than replacing the character, right?
Is there some other way I should "look/ask" for the selected value?
*Take into account, that I'am not looking for a solution with an UpdatePanel. I know, that using an UpdatePanel would result in the DDL value being sucessfully selected after the Postback, but that is NOT the answer I'm looking for here.
Thank you for any input.
If you still need to use the Request.Form.Get or Request.Params you should call it on ddlProdukt.UniqueID as it's separator is '$' versus '_' on the .ClientID
As requested an example. This code and the <asp:DropDownList ID="ddlProduct" runat="server"></asp:DropDownList> are on the aspx page, not the Master.
protected void Page_Load(object sender, EventArgs e)
{
//bind data not here
if (IsPostBack == false)
{
//but inside the ispostback check
ddlProduct.Items.Add(new ListItem("Item 1", "1"));
ddlProduct.Items.Add(new ListItem("Item 2", "2"));
ddlProduct.Items.Add(new ListItem("Item 3", "3"));
ddlProduct.DataBind();
}
}
protected void Button1_Click(object sender, EventArgs e)
{
Label1.Text = ddlProduct.SelectedValue;
}
I am displaying columns in a GridView and one of the columns is a dropdownlist. I want to be able to save the option selected in the dropdownlist as soon as something is selected. I have done this with one of the columns that has a textbox so I was hoping to do something similar with the DropDownList.
The code for the textbox and dropdownlist:
protected void gvPieceDetails_ItemDataBound(object sender, GridViewRowEventArgs e) {
if (e.Row.RowType == DataControlRowType.DataRow) {
JobPieceSerialNo SerNo = e.Row.DataItem as JobPieceSerialNo;
if (SerNo != null) {
TextBox txtComment = e.Row.FindControl("txtComment") as TextBox;
txtComment.Text = SerNo.Comment;
txtComment.Attributes.Add("onblur", "UpdateSerialComment(" + SerNo.ID.ToString() + ", this.value);");
DropDownList ddlReasons = (e.Row.FindControl("ddlReasons") as DropDownList);
DataSet dsReasons = DataUtils.GetUnapprovedReasons(Company.Current.CompanyID, "", true, "DBRIEF");
ddlReasons.DataSource = dsReasons;
ddlReasons.DataTextField = "Description";
ddlReasons.DataValueField = "Description";
ddlReasons.DataBind();
ddlReasons.Items.Insert(0, new ListItem("Reason"));
}
}
How to I create an update function for a dropdownlist?
protected void DDLReasons_SelectedIndexChanged(object sender, EventArgs e)
{
string sel = ddlReasons.SelectedValue.ToString();
}
public static void UpdateSerialReason(int SerNoID, string Reasons)
{
JobPieceSerialNo SerNo = new JobPieceSerialNo(SerNoID);
SerNo.Reason = sel; //can't find sel value
SerNo.Update();
}
Dropdownlist:
<asp:DropDownList ID="ddlReasons" runat="server" OnSelectedIndexChanged="DDLReasons_SelectedIndexChanged" AutoPostBack="true"></asp:DropDownList>
I created an OnSelectedIndexChanged function to get the selected value. But how do I then save that value? Is there a way to pass it into the UpdateSerialReason function?
Just move the string sel declaration outside the scope of DDLReasons_SelectedIndexChanged and get the Text of the SelectedItem since it's included in your data source.
private string sel;
protected void DDLReasons_SelectedIndexChanged(object sender, EventArgs e)
{
sel = ddlReasons.SelectedItem.Text;
}
public static void UpdateSerialReason(int SerNoID, string Reasons)
{
JobPieceSerialNo SerNo = new JobPieceSerialNo(SerNoID);
SerNo.Reason = sel; // Should now be available
SerNo.Update();
}
The way you had it previously it was only available in the local scope, i.e, inside the method in which it was being declared and used.
You can get selected value when you call your function:
UpdateSerialReason(/*Some SerNoID*/ 123456, ddlReasons.SelectedValue)
You will lose your value after postback is done if you save value to variable as Equalsk suggested. If you need to use your value on the other page you can save it in session.
If you are working within one asp.net page you can do as I suggested above. Then you can skip the postback on your DropDownList and call UpdateSerialReason when you need :)
And you might want to add property ViewStateMode="Enabled" and EnableViewState="true"
I have a radio button list whose items I need to add on Page_Load
aspx code
<asp:radioButtonList ID="radio1" runat="server" RepeatLayout="Flow" RepeatDirection="Horizontal">
</asp:radioButtonList>
code behind
protected void Page_Load(object sender, EventArgs e)
{
RadioButtonList radioList = (RadioButtonList)Page.FindControl("radio1");
radioList.Items.Add(new ListItem("Apple", "1"));
}
After the control reaches radioList.Items.Add
I keep getting the Object reference not set to instance of an object
error
What am I doing wrong?
You don't need to to do a FindCOntrol. As you used the runat="server" attributes, just get the reference of your RadioList via its name "radio1"
protected void Page_Load(object sender, EventArgs e)
{
radio1.Items.Add(new ListItem("Apple", "1"));
}
By using
RadioButtonList radioList = (RadioButtonList)Page.FindControl("radio1");
radioList.Items.Add(new ListItem("Apple", "1"));
you are not adding your list on the control on your page, but on an un-instanciated Radiobuttonlist called radioList.
If the page is reachable from the class, use
radio1.Items.Add(new ListItem("Apple", "1"));
you must add !ispostback
if (!IsPostBack)
{
radio1.Items.Add(new ListItem("Apple", "1"));
}
As an alternative to using the < asp: **> tools -
I needed to reuse a radio option which relies on a lot of jQuery integration in the site. (Also wanted to avoid just CSS hiding the content within the html code of the aspx page.)
The radio buttons needed only appear in an 'edit' page depending on security ACU level logic within the codebehind and rendered with currently stored item value data found in the db.
So I used the following:
string RadioOnChk1 = (db.fieldChecked == true) ? "checked='checked'" : "";
string RadioOnChk2 = (db.fieldChecked == false) ? "checked='checked'" : "";
if (ACU > 3)
{
// Create radio buttons with pre-checked
StringBuilder RadioButtns = new StringBuilder(); // Form input values
{
RadioButtns.Append("<p><label><input type=\"radio\" id=\"radiocomm1\" name=\"custmComm\" value=\"1\"");
RadioButtns.Append(RateIncChk1 + "/>Included or </label>");
RadioButtns.Append("<label><input type=\"radio\" id=\"radiocomm2\" name=\"custmComm\" value=\"2\"");
RadioButtns.Append(RateIncChk2 + "/>Excluded</label>");
RadioButtns.Append("</p>");
}
htmlVariable = (RadioButtns.ToString());
}
It works.. Is this a wrong way of going about it?
have a radiobutton list which I am filling with Strings and would like to know how to get in a given time the value of the selected element and throw it into a String for example. but with the command SelectedValue and SelectedItem only have null values.
This radio button list is filled several times during the execution of the same page.
//Where do you fill the RadioButtonList
public void MostraImagensCarrefadas()
{
List<String> files = new manFile().getListFilesForDirectory(this, MAE.DIRETORIO_TEMP_IMG);
rbImagemPrincipal.Items.Clear();
if (files != null)
{
foreach (String item in files)
{
rbImagemPrincipal.Items.Add(new ListItem(item));
}
}
}
//As it is in aspx
<div>
<asp:RadioButtonList ID="rbImagemPrincipal" runat="server" RepeatDirection="Vertical" AutoPostBack="false" OnSelectedIndexChanged="rbImagemPrincipal_SelectedIndexChanged"></asp:RadioButtonList>
//where only encounter null values when trying to get the selected item (clicked)
//Nothing I do is the value obtained direferente null.
if (rbImagemPrincipal.SelectedItem != null)
{
if (rbImagemPrincipal.SelectedItem.ToString() == str)
{
imagem.imagemPrincipal = "SIM";
}
}
It seems that you're populating the RadioButtonList on the page load -
If so - make sure you surround your population of the RadioButtonList with an
If/Then/Postback block:
if not Page.IsPostBack then
' populate your RBL
end if
eg:
if (!IsPostBack)
{
loadradiobuttonlist();
}
First of all, this is the page let you know the value, not the application is getting it.
So, you need a ScriptManager and Timer, both are Ajax extensions. Add them to the page.
protected void Page_Load(object sender, EventArgs e)
{
Timer1.Interval = 2000; // set your interval
}
protected void Timer1_Tick(object sender, EventArgs e)
{
int result = RadioButtonList1.SelectedIndex;
}
result is your radiobuttonlist selection index. Use it to select item from list.
I am dynamically adding a custom user control to an update panel. My user control contains two dropdownlists and a textbox. When a control outside of the update panel triggers a postsback, I am re-adding the user control to the update panel.
The problem is...on postback when I re-add the user controls, it's firing the "SelectedIndexChanged" event of the dropdownlists inside the user control. Even if the selectedindex did not change since the last postback.
Any ideas?
I can post the code if necessary, but there's quite a bit in this particular scenario.
Thanks in advance!
EDIT...CODE ADDED BELOW
*.ASCX
<asp:DropDownList ID="ddlColumns" OnSelectedIndexChanged="ddlColumns_SelectedChanged" AppendDataBoundItems="true" AutoPostBack="true" runat="server">
*.ASCX.CS
List<dataColumnSpecs> dataColumns = new List<dataColumnSpecs>();
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
fillDDLColumns();
}
}
public void fillDataColumnsList()
{
dataColumns.Clear();
//COMMON GETDATATABLE RETURNS A DATA TABLE POPULATED WITH THE RESULTS FROM THE STORED PROC COMMAND
DataTable dt = common.getDataTable(storedProcs.SELECT_COLUMNS, new List<SqlParameter>());
foreach (DataRow dr in dt.Rows)
{
dataColumns.Add(new dataColumnSpecs(dr["columnName"].ToString(), dr["friendlyName"].ToString(), dr["dataType"].ToString(), (int)dr["dataSize"]));
}
}
public void fillDDLColumns()
{
fillDataColumnsList();
ddlColumns.Items.Clear();
foreach (dataColumnSpecs dcs in dataColumns)
{
ListItem li = new ListItem();
li.Text = dcs.friendlyName;
li.Value = dcs.columnName;
ddlColumns.Items.Add(li);
}
ddlColumns.Items.Insert(0, new ListItem(" -SELECT A COLUMN- ", ""));
ddlColumns.DataBind();
}
protected void ddlColumns_SelectedChanged(object sender, EventArgs e)
{
//THIS CODE IS BEING FIRED WHEN A BUTTON ON THE PARENT *.ASPX IS CLICKED
}
*.ASPX
<asp:UpdatePanel ID="upControls" runat="server">
<ContentTemplate>
<asp:Button ID="btnAddControl" runat="server" Text="+" OnClick="btnAddControl_Click" />
</ContentTemplate>
</asp:UpdatePanel>
<asp:Button ID="btnGo" runat="server" Text="Go" OnClick="btnGo_Click" ValidationGroup="vgGo" />
<asp:GridView...
*.ASPX.CS
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
uc_Counter = 0;
addControl();
gridview_DataBind();
}
else
{
reloadControls();
}
}
protected void btnGo_Click(object sender, EventArgs e)
{
if (Page.IsValid)
{
//THIS BUTTON CLICK IS WHAT'S TRIGGERING THE
//SELECTEDINDEXCHANGED EVENT TO FIRE ON MY *.ASCX
gridview_DataBind();
}
}
private void reloadControls()
{
int count = this.uc_Counter;
for (int i = 0; i < count; i++)
{
Control myUserControl = Page.LoadControl("~/Controls/myUserControl.ascx");
myUserControl.ID = "scID_" + i;
upControls.ContentTemplateContainer.Controls.AddAt(i, myUserControl);
((customUserControl)myUserControl).fillDDLColumns();
}
}
private void addControl()
{
Control myUserControl = Page.LoadControl("~/Controls/myUserControl.ascx");
myUserControl.ID = "scID_" + uc_Counter.ToString();
upControls.ContentTemplateContainer.Controls.AddAt(upControls.ContentTemplateContainer.Controls.IndexOf(btnAddControl), myUserControl);
//((customUserControl)myUserControl).fillDDLColumns();
this.uc_Counter++;
}
protected int uc_Counter
{
get { return (int)ViewState["uc_Counter"]; }
set { ViewState["uc_Counter"] = value; }
}
Even though this is already answered I want to put an answer here since I've recently tangled with this problem and I couldn't find an answer anywhere that helped me but I did find a solution after a lot of digging into the code.
For me, the reason why this was happening was due to someone overwriting PageStatePersister to change how the viewstate hidden field is rendered. Why do that? I found my answer here.
One of the greatest problems when trying to optimize an ASP.NET page to be more search engine friendly is the view state hidden field. Most search engines give more score to the content of the firsts[sic] thousands of bytes of the document so if your first 2 KB are view state junk your pages are penalized. So the goal here is to move the view state data as down as possible.
What the code I encountered did was blank out the __VIEWSTATE hidden fields and create a view_state hidden field towards the bottom of the page. The problem with this is that it totally mucked up the viewstate and I was getting dropdownlists reported as being changed when they weren't, as well as having all dropdownlists going through the same handler on submit. It was a mess. My solution was to turn off this custom persister on this page only so I wouldn't have to compensate for all this weirdness.
protected override PageStatePersister PageStatePersister
{
get
{
if (LoginRedirectUrl == "/the_page_in_question.aspx")
{
return new HiddenFieldPageStatePersister(Page);
}
return new CustomPageStatePersister(this);
}
}
This allowed me to have my proper viewstate for the page I needed it on but kept the SEO code for the rest of the site. Hope this helps someone.
I found my answer in this post .net DropDownList gets cleared after postback
I changed my counter that I was storing in the viewstate to a session variable.
Then I moved my reloadControls() function from the Page_Load of the *.ASPX to the Page_Init.
The key was dynamically adding my user control in the Page_Init so it would be a member of the page before the Viewstate was applied to controls on the page.