DropDownList selected item always first item in list - asp.net

I have a DropDownList in a user control; however, no matter what I do I can't get any of the "selected" properties (SelectedItem, SelectedIndex, SelectedValue) to populate correctly. The value of all three of these properties is the first item in my list no matter which item was actually selected.
<asp:DropDownList ID="ParticipantsSelectList" runat="server">
<asp:ListItem Value="">Please select a team...</asp:ListItem>
<asp:ListItem value="{D37EFA0C-988A-4A2A-8D6E-80E3BAE00DEE}">Blue Team</asp:ListItem>
<asp:ListItem value="{7543E282-C9B8-435A-86A2-70E8E3BB38E5}">Green Team</asp:ListItem>
<asp:ListItem value="{F6BEF34A-215E-4179-9F4C-68F7C43D755F}">Orange Team</asp:ListItem>
<asp:ListItem value="{D50AD44A-686A-4BD3-B62E-D70ABF153AE5}">Red Team</asp:ListItem>
<asp:ListItem value="{DEFB7DA6-B0FF-4C36-A015-F3E8BC7AECA2}">Yellow Team</asp:ListItem>
<asp:ListItem value="{D37EFA0C-988A-4A2A-8D6E-80E3BAE00DEE},{7543E282-C9B8-435A-86A2-70E8E3BB38E5},{F6BEF34A-215E-4179-9F4C-68F7C43D755F},{D50AD44A-686A-4BD3-B62E-D70ABF153AE5},{DEFB7DA6-B0FF-4C36-A015-F3E8BC7AECA2}">All Teams</asp:ListItem>
</asp:DropDownList>
<asp:Button runat="server" Text="Submit" />
private void Page_Load(object sender, EventArgs e)
{
if (!String.IsNullOrEmpty(ParticipantsSelectList.SelectedValue)) // SelectedValue is always empty string (value of the first item in the list)
{
resultsPanel.Visible = true;
selectTeamLabel.Visible = false;
GenerateResultsTable();
}
else
{
resultsPanel.Visible = false;
selectTeamLabel.Visible = true;
}
}

Try using !Page.IsPostBack in Page_Load
private void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
//Your Code....
}
}

Related

how to enable/disable a textbox based on dropdown list value

I have 2 dropdown list values and for 1 of it when selected I want the one textbox out of 2 to get disabled.
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
if (DropDownList1.SelectedValue=="Admin")
TextBox2.Enabled = false;
else
TextBox2.Enabled = true;
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
if (DropDownList1.SelectedItem.Text.ToString()=="Admin")
TextBox2.Enabled = false;
else
TextBox2.Enabled = true;
}
Example:
<asp:DropDownList ID="DropDownList1" runat="server" CssClass="form-control">
<asp:ListItem Text="Admin" Value="1" />
<asp:ListItem Text="Other" Value="2" />
</asp:DropDownList>
If do you want to use Value, you can use "DropDownList1.SelectedValue.ToString()=="1""
If do you want to use Text, you can use "DropDownList1.SelectedItem.Text.ToString()=="Admin" "

DropDownList's SelectedIndexChanged event calls all events

i'm using Asp .Net Web Forms. i have 2 dropDown list and 1 input field. I want when i change the item on the dropDown list or the field value to call some event but it calls all the events.
for example if i change size it calls Size_SelectedIndexChanged, then Color_SelectedIndexChanged, and then txtKolicina_TextChanged
if i change color it calls Color_SelectedIndexChanged, than Size_SelectedIndexChanged and then txtKolicina_TextChanged.
Any help?
<asp:DropDownList ID="Colors" runat="server" AutoPostBack="true" CssClass="form-control detal-page-input" Style="height: 30px;" OnSelectedIndexChanged="Colors_SelectedIndexChanged" AppendDataBoundItems="True" DataSourceID="LinqDataSource3" DataTextField="color" DataValueField="color" >
<asp:ListItem Text="" Value=""></asp:ListItem>
</asp:DropDownList>
<asp:DropDownList ID="Size" runat="server" OnSelectedIndexChanged="Size_SelectedIndexChanged" AppendDataBoundItems="true" AutoPostBack="true" CssClass="form-control detal-page-input" Style="height: 30px;" DataSourceID="LinqDataSource2" DataTextField="size" DataValueField="size" EnableViewState="true">
<asp:ListItem Text="" Value=""></asp:ListItem>
</asp:DropDownList>
<asp:TextBox Name="txtKolicina" ID="txtKolicina" runat="server" CssClass="form-control form-numberone detal-page-input" OnTextChanged="txtKolicina_TextChanged" ></asp:TextBox>
this is backEnd
protected void Size_SelectedIndexChanged(object sender, EventArgs e)
{
//do something
}
protected void Colors_SelectedIndexChanged(object sender, EventArgs e)
{
//do something
}
protected void txtKolicina_TextChanged(object sender, EventArgs e)
{
//do something
}
UPDATE
public string[] GetColor()
{
CMS_Shop_ModuleDataContext db = new CMS_Shop_ModuleDataContext();
var color = (from p in db.CMS_Articles
where
p.articleID == int.Parse(HiddenFieldArticalId.Value) ||
p.sameAsArticleID == int.Parse(HiddenFieldArticalId.Value)
//where p.articleID == 10049 || p.sameAsArticleID == 10049
select p.color).Distinct();
return color.ToArray();
}
public int GetColorCount()
{
CMS_Shop_ModuleDataContext db = new CMS_Shop_ModuleDataContext();
var color = (from p in db.CMS_Articles
where (p.articleID == int.Parse(HiddenFieldArticalId.Value)
|| p.sameAsArticleID == int.Parse(HiddenFieldArticalId.Value))
&& p.color != ""
select p.color);
return color.Distinct().Count();
}
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
if (GetColorCount() == 0)
{
Colors.Visible = false;
lblBoja.Visible = false;
}
else
{
Colors.Visible = true;
lblBoja.Visible = true;
}
Looks like you use View State and repopulate your DropDownLists in code behind on Postback. Can you show OnInit and OnLoad ?
Or just try this code:
if (!IsPostBack) {
// populate all drop downs lists
}
Ok i found what was the problem.
a change
EnableViewState="false"
to
EnableViewState="true"

dropdown selected index change without postback no update panel needed

i am trying to fill text box from database on dropdownlist selected index changed without page post back.
i tried the following code it does not work
<script runat="server">
private String queryString;
protected void Page_PreRender(object sender, EventArgs e)
{
if (!String.IsNullOrEmpty(queryString))
{
Class1 obj = new Class1();
if (ddlEmployee.SelectedIndex >= 0)
{
System.Data.DataSet ds = obj.BindDataSet("Select ID,Email from EmployeeDetails where ID=" + ddlEmployee.SelectedValue);
txtEmail.Text = ds.Tables[0].Rows[0][1].ToString();
}
}
}
protected void Page_Init(object sender, EventArgs e)
{
queryString = "?foo=bar;a=b";
}
</script>
Look into ASP.NET PageMethods. Here's a sample:
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true"></asp:ScriptManager>
<asp:DropDownList ID="ddlEmployee" runat="server">
<asp:ListItem Selected="True" Value="1">One</asp:ListItem>
<asp:ListItem Value="2">Two</asp:ListItem>
<asp:ListItem Value="3">Three</asp:ListItem>
<asp:ListItem Value="4">Four</asp:ListItem>
<asp:ListItem Value="5">Five</asp:ListItem>
</asp:DropDownList>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
</form>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<script type="text/javascript">
$(function () {
$("#ddlEmployee").on("change", function () {
PageMethods.SetText($(this).val(), OnSetCompleted);
});
function OnSetCompleted(result) {
$("#TextBox1").val(result);
}
</script>
In the code-behind:
[System.Web.Services.WebMethod()]
[System.Web.Script.Services.ScriptMethod()]
public static string SetText(string id)
{
//do your DB stuff here
return "You selected " + id;
}
Check these:
http://weblogs.asp.net/jalpeshpvadgama/archive/2012/01/07/asp-net-page-methods-with-parameters.aspx
http://encosia.com/using-jquery-to-directly-call-aspnet-ajax-page-methods/

View state on dropdown control

<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:Button ID="Button1" runat="server" UseSubmitBehavior="false"
OnClick="Button1_Click" OnClientClick="this.disabled = true; this.value = 'Submitting...'; "
Text="Click Me…" /></div>
<asp:DropDownList ID = "dListFruits" runat ="server" EnableViewState ="true"></asp:DropDownList>
protected void Page_Load(object sender, EventArgs e)
{
ArrayList aList = new ArrayList();
aList.Add("Apples");
aList.Add("Oranges");
if (!Page.IsPostBack)
{
dListFruits.DataSource = aList;
dListFruits.DataBind();
TextBox1.Text = "Hi";
}
}
protected void Button1_Click(object sender, EventArgs e)
{
}
When i had a break point in a button click event , this peice of statement "dListFruits.DataSource" shows null while debugging. I thought view state will be applied before load event triggered. But when i see the page items are appended into the dropdown list. So view state will be applied just before render?
Just check out the Items collection of the dropdownlist. Viewstate stores the items collection of dropdownlist control.

RadioButtonList Postback Issues

Environment: ASP NET 2.0 - Production Server does not have Ajax Control Toolkit so no real Control toolkit to use here.
3 RadioButtons List:
List one loads, after postback, the item from list one is used to select a Lab value.
Once a lab value is selected a 3rd radiobuttonlist will populate. There are some textboxes but they are not shown in example. The textboxes postback themselves on changes. If both textboxes are
not empty, a record is created for the session.
Now if the 3rd radiobuttonlist is changed from the default a series of 3 hidden user controls appear which represent 3 levels of reasons for the change ( child/parent records in database ).
The problem I am having is when I select a different item on the radiobuttonlist the radiobutton 3 OnSelectedIndex is firing after my user controls fire. My user controls need the value of the 3rd list to go to the database and get the correct set of records associated with the lab.
The problem is because the last radiobuttonlist is not processed until after the web controls loads, the code to mount the user controls never happens.
Here is the basic HTML code:
<asp:RadioButtonList ID="rdoLab" runat="server" OnSelectedIndexChanged="rdoLab_OnSelectedIndexChange">
</asp:RadioButtonList>
<asp:TextBox ID="textbox1" runat="server" OnTextChanged="TextBoxProcess" />
<asp:TextBox ID="textbox2" runat="server" OnTextChanged="TextBoxProcess" />
<asp:RadioButtonList ID="rdoPrimary" RepeatColumns="3" OnSelectedIndexChanged="rdoPrimary_OnSelectedIndexChanged" runat="server" ToolTip="Select Normal, Hypo or Hyper - Normal is default value." AutoPostBack="True" >
<asp:ListItem Value="3" Text="Normal" Selected="true"/>
<asp:ListItem Value="1" Text="Hypo" />
<asp:ListItem Value="2" Text="Hyper" />
</asp:RadioButtonList>
<asp:Panel ID="UpdLab" runat="server" Visible="true" EnableViewState="true">
<asp:Table ID="tblAdmin" runat="server">
<asp:TableRow>
<asp:TableCell runat="server" id="tblCell1" Visible="false" CssClass="tdCell" VerticalAlign="top">
<uc1:Lab ID="Lab1" runat="server" EnableViewState="true" EnableTheming="true" />
</asp:TableCell>
<asp:TableCell runat="server" ID="tblCell2" Visible="false" CssClass="tdCell" VerticalAlign="top">
<uc1:Lab ID="Lab2" runat="server" EnableViewState="true" EnableTheming="true" />
</asp:TableCell>
<asp:TableCell runat="server" ID="tblCell3" Visible="false" CssClass="tdCell" VerticalAlign="top">
<uc1:Lab ID="Lab3" runat="server" EnableViewState="true" EnableTheming="true" />
</asp:TableCell>
</asp:TableRow>
</asp:Table>
</asp:Panel>
Here is the page behind:
protected override void OnPreLoad(EventArgs e)
{
base.OnPreLoad(e);
GetSessionVars();
if (CommonUI.strTest((string)Session["rdoLabs"]) && CommonUI.strTest((string)Session["rdoPrimary"]) && Convert.ToString(hrdoLabs.Value) == (string)Session["rdoLabs"])
{
divLabLvl.Visible = true;
// Get cboListItems from the web user controls...
Session["ArrLstItems"] = "";
ArrayList ArrLstItems = new ArrayList();
ArrayList GetWuc = GetWUCS();
for (int i = 0; i < GetWuc.Count; i++)
{
Lab wuc = (Lab)GetWuc[i];
CheckBoxList cboItemList = (CheckBoxList)wuc.FindControl("cboItems");
string cboItems = GetCboItemList(cboItemList);
HiddenField hcboItems = (HiddenField)wuc.FindControl("hcboItems");
}
Session["ArrLstItems"] = (ArrayList)ArrLstItems;
}
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DbDataReader ddrGrp = rdoGroups();
if (ddrGrp.HasRows)
{
rdoGroup.DataSource = ddrGrp;
rdoGroup.DataBind();
}
ddrGrp.Close();
}
else
{
DbDataReader ddrLab = rdoUserLabs();
if (ddrLab.HasRows)
{
rdoLabs.DataSource = ddrLab;
rdoLabs.DataBind();
if (CommonUI.strTest((string)Session["rdoLabs"]))
{
if (Convert.ToInt32(Session["rdoLabs"]) > 0)
{
rdoLabs.SelectedValue = (string)Session["rdoLabs"];
SetLabCss();
}
}
}
ddrLab.Close();
}
}
protected void rdoGroup_OnSelectedIndexChanged(object sender, EventArgs e)
{
//...do some stuff
}
protected void rdoLabs_OnSelectedIndexChanged(object sender, EventArgs e)
{
//... reload
}
protected DbDataReader rdoGroups()
{
int group_type_id = GroupTypeId();
Group grp = new Group();
return grp.GetGroups(group_type_id);
}
protected DbDataReader rdoUserLabs()
{
RadioButtonList rdoGrp = (RadioButtonList)CommonUI.FindCtrlRecursive(this.Master, "rdoGroup");
int GroupId = Convert.ToInt32(rdoGrp.SelectedValue);
LabAbnormalReasons lar = new LabAbnormalReasons();
return lar.GetLabsList(GroupId);
}
protected void rdoPrimary_OnSelectedIndexChanged(object sender, EventArgs e)
{
Session["Save"] = ((RadioButtonList)sender).ID;
RadioButtonList rdoGroups = (RadioButtonList)CommonUI.FindCtrlRecursive(this.Master, "rdoGroup");
RadioButtonList rdoLabs = (RadioButtonList)CommonUI.FindCtrlRecursive(this.Master, "rdoLabs");
int UserId = Convert.ToInt32(Session["UserId"]);
int DocId = Convert.ToInt32(Session["DocId"]);
SubmitLab_Data(arrLstItems, arrOthers);
}
protected void GetSessionVars()
{
RadioButtonList rdoGroup = (RadioButtonList)CommonUI.FindCtrlRecursive(this.Master, "rdoGroup");
RadioButtonList rdoPrimary = (RadioButtonList)CommonUI.FindCtrlRecursive(this.Master, "rdoPrimary");
RadioButtonList rdoLabs = (RadioButtonList)CommonUI.FindCtrlRecursive(this.Master, "rdoLabs");
if (rdoGroup.SelectedIndex != -1)
{
Session["rdoGroup"] = (string)rdoGroup.SelectedValue;
}
if (rdoLabs.SelectedIndex != -1)
{
Session["rdoLabs"] = (string)rdoLabs.SelectedValue;
}
if (rdoPrimary.SelectedIndex != -1)
{
Session["rdoPrimary"] = (string)rdoPrimary.SelectedValue;
}
}
Here is example of user code:
THIS CODE NEVER FIRES BECAUSE the 3rd Button List data is not available here :
protected void Page_Load(object sender, EventArgs e)
{
/////*
//// * lab & Primary have been selected...
//// */
int lvl = SetLvlId();
int par_id = GetParentLvl();
Lab wuc = GetWuc(lvl);
if (wuc != null)
{
if (CommonUI.strTest(Convert.ToString(Session["rdoLabs"])) && CommonUI.strTest(Convert.ToString(Session["rdoPrimary"])))
{
// data in data base for this user, lab, doc identifier...
if (Convert.ToInt32(Session["rdoPrimary"]) > 0
{
// have user hdr data - see if item data is mapped...
// do some stuff here
}
}
}
}
I hope this is clear. I've att
---*--- Since original posting:
added simple javascript/OnDataBound
function Primary(object)
{
alert("Value Clicked :" + object);
}
protected void rdoPrimary_DataBound(object sender, EventArgs e)
{
RadioButtonList rdlPrimary = (RadioButtonList)sender;
foreach (ListItem li in rdlPrimary.Items)
{
li.Attributes.Add("onclick", "javascript:Primary('" + li.Value + "')");
}
}
Store and retrieve the values you want to retain in SaveViewState and LoadViewState methods and see if that works for you? Also look to the earlier and later lifecycle events for handling the logic - Init and OnPreRender. This has worked for me in the past.

Resources