I'm having a hard time figuring this out and I hope you guys would help me.
I have a page called Index.aspx with a DropDownList that is a separate UserControl class (because it will be used in other pages). Here's the code for that:
UcSelecionarLocal.ascx:
<%# Control Language="C#" AutoEventWireup="true"
CodeBehind="UcSelecionarLocal.ascx.cs"
Inherits="QuickMassage.uc.UcSelecionarLocal" %>
<asp:DropDownList ID="ddlLocais" runat="server"
CssClass="span4 dropdown-toggle" AutoPostBack="true">
</asp:DropDownList>
UcSelecionarLocal.ascx.cs:
public partial class UcSelecionarLocal : UserControl {
protected void Page_Load(object sender, EventArgs e) {
if (!this.IsPostBack) {
PreencherLocais();
}
}
private void PreencherLocais() {
ddlLocais.Items.Clear();
ddlLocais.Items.Add(new ListItem("Selecione", "0"));
ControleLocal controle = new ControleLocal();
DataTable tab = controle.ListarLocais();
foreach (DataRow row in tab.Rows) {
ddlLocais.Items.Add(new ListItem(row["Descricao"].ToString(),
row["ID"].ToString()));
}
}
}
This control is placed in Index.aspx and loads its values correctly. The form that it's contained in, has the action set to agendamentos.aspx. When I change the ddlist, the page is submitted to the forms action page, as it should be.
On the other page the problems begin: I get the parameters posted to this page and one of them is the ddlist value. In the immediate window, I check the value and it's there, let's say that it is 1.
To make long story short, I have this code:
agendamentos.aspx.cs:
protected void Page_Load(object sender, EventArgs e) {
DropDownList locais = ObterComponenteListaLocais();
try {
locais.SelectedIndex =
int.Parse(HttpContext.Current.Request["ucSelLocal$ddlLocais"]);
}
While debugging, I see that locais.SelectedIndex is -1. After the assignment it remains -1. The page loads and then I change the ddlist value again to 2. When debugging the same code above, I see that the locais.SelectedIndex is now 1. Again, setting it to 2, as it would normally be, produces no effect. If I change the ddlist again to 3, the SelectedIndex becomes 2 and does not take the value 3.
In other words: the value of the index in a newly loaded page is the value of the page that was loaded before.
Could you guys help me?
This is because the Page_Load event is firing in your page before the user control is loading. Do this:
public partial class UcSelecionarLocal : UserControl
{
protected void Page_Load(object sender, EventArgs e)
{
}
public void PreencherLocais()
{
ddlLocais.Items.Clear();
ddlLocais.Items.Add(new ListItem("Selecione", "0"));
ControleLocal controle = new ControleLocal();
DataTable tab = controle.ListarLocais();
foreach (DataRow row in tab.Rows)
{
ddlLocais.Items.Add(new ListItem(row["Descricao"].ToString(), row["ID"].ToString()));
}
}
}
Then in your aspx page:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
this.idOfYourUserControl.PreencherLocais();
DropDownList locais = ObterComponenteListaLocais();
try {
locais.SelectedIndex =
int.Parse(HttpContext.Current.Request["ucSelLocal$ddlLocais"]);
}
}
Also because your question is a little confusing, an important note is that Page_Load fires before data is captured from controls that post back data. So that's a bad place to get their information because it will be what it was previously. That's why you need to create a function that fires on something like a button click that will execute after the controls data have been loaded.
Related
I have a Grid and on top of the grid, I like am showing a label as such:
<asp:Label ID="lblMsg" runat="server" ForeColor="Red"></asp:Label>
On delete of a row in my grid I have the following code:
protected void RadGrid1_DeleteCommand(object sender, GridCommandEventArgs e)
{
if (!(User.IsInRole("Administrator")))
{
lblMsg.Text = "Must be an Admin in delete.";
return;
}
NOTE: The debugger does go to where I have the label text displayed but it simply does not display on the page. :
lblMsg.Text = "Must be an Admin in delete.";
NOTE: If I have the same code in the page load, the label text shows up fine on the page Also DO NOT have (!IsPostBack){} in my code.
Therein lies your issue. When your page is posting back the label is getting assigned the value:
lblMsg.Text = "Must be an Admin in delete.";
But Page_Load gets called again. So your Page_Load should look like this
protected void Page_Load(object sender, EventArgs e) {
if(!IsPostBack) {
//Populate my page
}
}
This will hold true for almost every page you write in ASP.NET
I'm trying to pass a value from a User Control to a code behind without luck. I can write the correct value (IDuser_uc) on the aspx page but I can't pass it to the code behind. Any tips?
User Control
protected void FormView_IDuser_DataBound(object sender, EventArgs e)
{
Label IDuserText = FormView_IDuser.FindControl("IDuserLabel") as Label;
IDuser_uc = Convert.ToString(IDuserText.Text);
}
ASPX page
<uc4:IDuser id="IDuser" runat="server" />
<% Response.Write(IDuser.IDuser_uc); // Here correct value %>
Code Behind
protected void Page_Load(object sender, EventArgs e)
{
SqlDataSource_userConnections.SelectParameters["IDuser_par"].DefaultValue = IDuser.IDuser_uc ; // Here NO value
Response.Write("Connections :" + IDuser.IDuser_uc); // Here NO value
}
UPDATE
The problem was due to the fact that the User Control is run after the PageLoad which explains why I got an empty string. To solve the problem I used Page_PreRender instead of Page_Load on the code behind page.
Create a public method in your user control. When you post back the page have the Parent.aspx page call the user control method. Example....
In your User Control:
Public string GetUserControlValue()
{
return Label IDuserText;
}
In your Parent ASPX Pgae
var UserControlString = IDuser_uc.GetUserControlValue();
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?
I have a drop down which has the list of delegates. When the user selects a delegate then I populate the available meet-timings in the second dropdown using the selectedindexchange event of the 1st dropdown
Aspx page
<asp:DropDownList ID="delegate_ddl" runat="server" AutoPostBack="True" OnSelectedIndexChanged="ddldelegates_SelectedIndexChanged" Width="200px"></asp:DropDownList>
<asp:DropDownList ID="delegatetime_ddl" runat="server" Width="90px"></asp:DropDownList>
<asp:Button ID="adddelegate" runat="server" Text="Add" onclick="adddelegate_Click"/>
.cs page
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DataSet ds1 = getdata.getdelegatelist();
delegate_ddl.DataSource = ds1.Tables[0];
delegate_ddl.DataTextField = "DELEGATE_NAME";
delegate_ddl.DataValueField = "DELEGATE_ID";
delegate_ddl.DataBind();
delegate_ddl.Items.Insert(0, "--Select--");
}
}
protected void ddldelegates_SelectedIndexChanged(object sender, EventArgs e)
{
string delselection = delegate_ddl.SelectedValue.ToString();
DataSet ds2 = getdata.getdelegatetimelist(delselection);
if (ds2.Tables[0].Rows.Count > 0)
{
delegatetime_ddl.DataSource = ds2.Tables[0];
delegatetime_ddl.DataTextField = "TIMESLOT";
delegatetime_ddl.DataValueField = "TIMEID";
delegatetime_ddl.DataBind();
}
else
{
time_lbl.Text = "No slots Open";
}
}
protected void adddelegate_Click(object sender, EventArgs e)
{
string delegateselected = delegate_ddl.SelectedValue.ToString();
string timeslotselected = delegatetime_ddl.SelectedValue.ToString();
getdata.delegatemeetinsert(personidd, delegateselected, timeslotselected);
}
Now the data gets inserted – but my question here is
As soon as the user click add button I would like to display the delegate selected and the time slot selected in a some sort of a grid view or dynamic table below with a delete option.
Can someone please provide a code sample in C# to achieve the above
Instead of using Gridview for displaying data use some basic control like Labels,it will reduce lot's of unncessary code. use Asp.net 'Panel' control and encapsulate all label and button(for delete purpose) into Panel then hide/show according to need. here is the outline of code that might help you,
if(!page.IsPostBack) // This goes into Page_Load
{
Panel1.Visible=false;
}
protected void adddelegate_Click(object sender, EventArgs e) // add this additional code
{
Panel.Visible=True;
GetDelegate()// This method retrieve the delegate you inserted..
Lable1.Text= "Set here Delegate name you just Retrieved"
Label2.Text="Delegate time you retrived"
}
protected void BtnRemovedelegate_Click(object sender, EventArgs e)
{
string Personidd= retrieve person id
string delegateName= Lable1.text;
String timeslot=Label2.Text
SomeDeleteMethod(personidd, delegateName, timeslot);
Panel1.Visible=false;
}
Hope you get the idea..
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.