I'm trying to set the selected value of a DropDownList on Page_Load using a value that is saved into a Session variable. The DropDownList is already populated and the value is stored along with other info in a session. I'm creating an edit entry page and want to have all of the fields already populated with the info from the Session.
What I've done is populate TextBox with the Session Variables, but for the Advisors section I need the User to enter a number instead of a name. So I need to use a DropDownList to make sure that information is entered accurately. I've looked into methods of databinding, databound, using a data source, etc but it seemed like all of those DropDownLists were generated dynamically. Any help would be much appreciated.
My .aspx Code:
<asp:TextBox runat="server" ID="fname" MaxLength="100"></asp:TextBox>
<asp:DropDownList ID="advisors" runat="server">
<asp:ListItem Value="">Select Advisor</asp:ListItem>
<asp:ListItem Value="2">Joe Schmo</asp:ListItem>
</asp:DropDownList>
Code Behind:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
fname.Text = Session["fname"].ToString();
lname.Text = Session["lname"].ToString();
sex.Text = Session["sex"].ToString();
sid.Text = Session["sid"].ToString();
email.Text = Session["email"].ToString();
phone.Text = Session["phone"].ToString();
advisors.SelectedValue = Session["advisor"].ToString();
}
}
UPDATE:
So I'm dumb. The Session variable was storing the name "Joe Schmo" not the Value "2". The below code worked for me.
foreach (ListItem listItem in advisors.Items)
{
listItem.Selected = listItem.Text.Equals(Session["advisor"].ToString());
}
try this
foreach (ListItem listItem in advisors.Items)
{
if(listItem.Text.Equals(Session["advisor"].ToString())
DropDownList1.Items.FindByValue(Session["advisor"].ToString()).Selected = true;
}
Related
At the moment i have a method that retrieves a list of name from my database and return as an arraylist.
public static ArrayList GenerateFolderLocation(String username)
{
// Get User ID
SqlDataReader sqlUserID = GetUserInformation(username);
sqlUserID.Read();
int userid = int.Parse(sqlUserID["userid"].ToString());
SqlCommand cmd = new SqlCommand("SELECT distinct foldername FROM mb_folder WHERE userid=#userid", SQLGetMBoxConnection());
cmd.Parameters.AddWithValue("#userid", userid);
SqlDataReader sqldr = cmd.ExecuteReader();
ArrayList locationList = new ArrayList();
while (sqldr.Read())
{
locationList.Add(sqldr["foldername"].ToString());
}
locationList.Sort();
return locationList;
}
And in my page load method, i use DataSource and DataBind to fill up a dropdownlist i have on my main page. Note UploadLocation is the id of my dropdownlist
UploadLocation.DataSource= MBFolder.GenerateFolderLocation(Context.User.Identity.Name);
UploadLocation.DataBind();
And in my main page i have this dropdownlist and i also have a submit button
<asp:DropDownList ID="UploadLocation" runat="server"
AutoEventWireup="true" EnableViewState="true">
</asp:DropDownList>
<asp:Button ID="NewUploadFile" runat="server" Text="Upload" OnClick="NewUploadFile_Click" ValidationGroup="UploadFileValidation" AutoPostBack="true"/>
What my problem is that when i click my submit button it fires the "NewUploadFile_Click" and in that method i want to retrieve the selected value of my dropdownlist. However right now i am able to retrieve the value but it is the first value in my dropdownlist. So for example, in my arraylist there would be (test1,test2,test3) and if i select "test2" my method would retrieve "test1" instead.
In "NewUploadFile_click" i use UploadLocation.SelectedItem.Text; to get the selected value. What am i doing wrong? How can i retrieve the selected data. Thx
Try wrapping your list initialisation code within an !IsPostBack {} section in the PageLoad Event.
ie in Page_Load
if (!IsPostback)
{
... Initialise List here
}
Looks like you may be rebinding the list before you have got the data you need.
When you are calling a method to bind dropdownlist, try to add it inside
In PageLoad event:
if(!IsPostBack)
{
fillvalues();
}
So, It will not fire everytime you change your selections
Try setting AutoPostBack="true"; into your DropDownList
<asp:DropDownList ID="UploadLocation" runat="server"
AutoEventWireup="true" EnableViewState="true" AutoPostBack="true";>
</asp:DropDownList>
Confirm that you page level ViewState is enabled
and also confirm that your databinding code is inside !IsPostback condition
if (!IsPostback)
{
.... databinding code..
}
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();
EDIT: So I found that this line listItem.Value = rdr["lvl"].ToString(); was adding the same value for each item in the dropdown. Since each text item had the same value, I guess it always defaulted to the first text item. I'm now passing lvl through another query instead of the dropdown. Thanks for all the helpful input!
I'm trying to accomplish a pretty simple task which I've done numerous times before. For some reason, I can't get my dropdown to correctly pass the SelectedItem and SelectedValue.
The SelectedItem and SelectedValue are always returned for the first item in the dropdown, regardless of which item I select.
What am I doing wrong?
Defining dropdown and button:
<asp:DropDownList ID="DropDownList1" runat="server" >
</asp:DropDownList>
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Button" />
Populating dropdown on PageLoad:
myConnection.Open();
SqlCommand rpt = new SqlCommand(getreports, myConnection);
SqlDataReader rdr = rpt.ExecuteReader();
if (!Page.IsPostBack)
{
while (rdr.Read())
{
ListItem listItem = new ListItem();
listItem.Text = rdr["manager"].ToString();
listItem.Value = rdr["lvl"].ToString();
DropDownList1.Items.Add(listItem);
}
rdr.Close();
myConnection.Close();
}
Code for button click that should pass SelectedItem and SelectedValue:
protected void Button1_Click(object sender, EventArgs e)
{
string user = DropDownList1.SelectedItem.Text;
string lvl = DropDownList1.SelectedValue;
Label1.Text = user;
Label2.Text = lvl;
}
I realized the same value was being assigned for each item. This was the reason the first item in the dropdown kept being passed regardless of the selection. As long as the values are different, all the above code works as expected.
(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
I have a textbox and a dropdownlist
the textbox has
<asp:TextBox ID="TxtInizioPeriodo" runat="server"
ontextchanged="InizioPeriodo_TextChanged" AutoPostBack="true" Width="100"></asp:TextBox>
i want if it changes the dropdownlist return to default value selected
i try to pur in page load this:
SelectDestinazione[i].SelectedValue = "";
but it now works.
how can i do?
thanks
In your code you have mentioned like
Array of Dropdownlist ie.,
SelectDestinazione[i].SelectedValue = "";
in the above code "i" selects dropdownlist object from the array of dropdownlists.
Kindly check that one. If its is the single dropdownlist box then use the below solution.
Copy & paste the below code in the server side during the text content change event.
protected void InizioPeriodo_TextChanged(object sender, EventArgs e)
{
SelectDestinazione.SelectedIndex = -1;
}
I assume SelectDestinazione is your dropdownlist
SelectDestinazione.clearSelection();