I fill a ASP Dropdownlist in the pageload
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
for (int i = 0; i < _maxStationsAnz; i++)
{
String stations = arrayList[1];
_allData = stations.Split(Convert.ToChar("/"));
_data = _allData[i].Split(Convert.ToChar(";"));
ddWeatherstations.Items.Add(_data[0]);
}
}
When a new station is selected, it should update informations. I use the OnSelectedIndexChanged attribute on my aspx site.
My code behind:
protected void ddWeatherstations_SelectedIndexChanged(object sender, EventArgs e)
{
for (int i = 0; i < _maxStationsAnz; i++)
{
if (ddWeatherstations.SelectedIndex == i)
{
lselected.Text = "Index changed!";
//unimportant code
//....
}
}
}
When I set a breakpoint and run the program and change the value of the dropdownlist, nothing happens.
You need to set AutoPostBack property of your dropdownlist ddWeatherstations to True.
Try This:
<asp:DropDownList ID="ddWeatherstations" runat="server" AutoPostBack="true"
OnSelectedIndexChanged="ddWeatherstations_SelectedIndexChanged">
</asp:DropDownList>
You need to set property AutoPostBack="true" but this will post back all of your page every time you select a different index of your DropDownList so I will suggest you to put your DropDownList in an AJAX Update Panel.
Related
I have a drop down list which will load up with a series of customer ID numbers. I then have a gridview control on my page with the select hyperlink. When i click on the link to select the row in gridview i would like my dropdown to change to that number.
Below is what i have tried but doesn't work:
for (int i = 0; i < GridView1.Rows.Count; i++)
{
if (!GridView1.SelectedIndex.Equals(-1))
{
DropDownList ddl;
ddl = (DropDownList)form1.FindControl("ddl_Customers");
ddl.SelectedValue = (String)GridView1.SelectedDataKey.Values[0];
}
}
Handle the SelectedIndexChanged event for GridView1
void GridView1_SelectedIndexChanged(Object sender, EventArgs e) {
ddl_Customers.SelectedValue = GridView1.SelectedDataKey.Value.ToString();
}
You can directly use GridView1.SelectedValue.ToString() for this. To use that, you should define a datakeyname like this: <asp:Gridview DataKeyNames="CustomerID">
Then all you need is this:
void GridView1_SelectedIndexChanged(Object sender, EventArgs e) {
ddl_Customers.SelectedValue = GridView1.SelectedValue.ToString();
}
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 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.
i'm using a HtmlInputCheckBox in a repeater by adding
<input id="CheckBox1" type="checkbox" runat="server" value='<%# Eval ("userid") %>' />
to repeater->ItemTemplate->table->tr->td and in the server side i'm using
protected void Button1_Click(object sender, EventArgs e)
{
for (int i = 0; i < UserRepeater.Items.Count; i++)
{
var chkBox = UserRepeater.Items[i].FindControl("CheckBox1") as HtmlInputCheckBox;
if (chkBox != null && chkBox.Checked)
{
//
}
}
}
i'm not programatically setting any checkbox to set - i'm checking them on the web page during test.
my var checkbox is always inchecked {Value = "1,2,3,4" Checked = false}, thx for helping me with that.
How are you populating your repeater - if you are doing it in page_load make sure it is protected for postbacks:
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
// populate your data
}
}
EDIT
This is assuming you are working with viewstate on - which is the case by default.
This may be to do with when you bind your repeater. If you are binding on Page_Load, the check boxes will be created after viewstate and post variables have been restored, so the value won't be on your checkboxes.
If possible, move the data bind to Page_Init; as this happens before viewstate/post values are restored your checkboxes will get the right values assigned. If you can't bind on Page_Init, then #Aristos's answer will do.