I have 2 dropdowns ddl1 and ddl2. When im setting selected value for ddl1 it works,but after setting selected value for ddl2 also changes the value of ddl1.I dont know how but its doing so.
aspx
<asp:DropDownList ID="ddlPickup" runat="server" CssClass="tb_date"
>
</asp:DropDownList>
Dropoff:
<asp:DropDownList ID="ddlDropoff" runat="server" CssClass="tb_date" >
</asp:DropDownList>
<asp:RadioButtonList ID="radiobuttonlist1" runat="server" AutoPostBack="True" OnSelectedIndexChanged="radiobuttonlist1_SelectedIndexChanged"
RepeatDirection="Horizontal">
<asp:ListItem Value="1">Day or Longer</asp:ListItem>
<asp:ListItem Value="2">1/2 Day</asp:ListItem>
<asp:ListItem Value="3">Hourly</asp:ListItem>
</asp:RadioButtonList>
code behind
protected void radiobuttonlist1_selectedindexchange(object sender, EventArgs e)
{
if(radiobuttonlist1.SelectedValue=="1")
{
Setddl();
}
}
public void Setddl()
{
if (ddlPickup.Items.Count > 0)
{
ddlPickup.Items.Clear();
}
if (ddlDropoff.Items.Count > 0)
{
ddlDropoff.Items.Clear();
}
ListItem li = new ListItem();
DateTime date = Convert.ToDateTime(StartDate.Text);
int day = Convert.ToInt32(date.DayOfWeek);
long itemid = Convert.ToInt64(ddlRentalItem.SelectedValue);
if (itemid != 0)
{
var dropoff = _objRitems.GetHourlyHourByDay(itemid, day);
if (dropoff.Count > 0)
{
int stimeh = Convert.ToDateTime(dropoff[0].OpenTime).Hour;
int etimeh = Convert.ToDateTime(dropoff[0].CloseTime).Hour;
DateTime dt = Convert.ToDateTime(dropoff[0].OpenTime);
for (int i = 0; i <= (etimeh - stimeh) * 2; i++)
{
string time = string.Format("{0:t}", dt);
li = new ListItem(time, time);
ddlPickup.Items.Add(li);
ddlDropoff.Items.Add(li);
dt = dt.AddMinutes(30);
}
ddlPickup.DataBind();
ddlDropoff.DataBind();
ddlPickup.SelectedValue=Request.QueryString["droptime"].ToString();
ddlDropoff.SelectedValue=Request.QueryString["droptime"].ToString();
//as soon as ddlDropoff SelectedValue assigns ddlPickup.SelectedValue changes to ddlDropoff.SelectedValue..Very Weird!!!
}
else
{
}
}
else
{
}
}
you need to write your dropdown code in below if condition.
if(!isPostBack)
{
}
Forget about ddlPickup_DataBound. Rely on the ViewState implicit in dropdown lists to repopulate the selected value. The ondatabound methods are unnecessary in this case.
Also you only need to bind the dropdowns once so on Page.IsPostBack - like the other poster has said
This would be the more standard way to deal with drop downs i.e.
Bind once
SelectedValue persists in after postbacks. No need for special work here
The way you are doing it - the databound will fire on each page load (after each dropdown if autopostback is true). The both dropdowns will repopulate every time - depending what yor have got in your Request collection. This isn't what you intend i assume and would account for the strange behaviour.
EDIT:
Just to be really clear this is the pattern that should be followed
Markup
<asp:DropDownList ID="ddlPickup" runat="server" ></asp:DropDownList>
<asp:DropDownList ID="ddlDropoff" runat="server" OnSelectedIndexChanged="selectedIndexEvent"></asp:DropDownList>
Code behind
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack)
{
BindDropDownLists();
}
}
protected void ddl2_selectedindexchange(object sender, EventArgs e)
{
//.. legit - do whatever is needed but don't reset selected value
}
protected void radiobuttonlist1_selectedindexchange(object sender, EventArgs e) {
{
BindDropDownLists();
SetInitialDropDownValues();
}
No ondatanound is needed
Related
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"
I have an item template within repeater:
<ItemTemplate>
<li>
<input type="radio"
value="<%# GetAssetId((Guid) (Container.DataItem)) %>"
name="AssetId"
<%# SelectAsset((Guid) Container.DataItem) %> />
</li>
</ItemTemplate>
I have a method that compares ids and decides whether to check the radio button.
protected string SelectAsset(Guid uniqueId)
{
if (uniqueId == GetSomeId())
return "checked=\"checked\"";
return string.Empty;
}
SelectAsset gets hit, but it doesn't select a radio button on a post back, but it does work if I just refresh the page. What am I doing wrong here?
Answer here: How to display "selected radio button" after refresh? says that it's not possible to achieve, is this really the case?
Thank you
Update
It appears that view state isn't available for simple controls if they don't have a runat attribute. I have solved this by using a custom GroupRadioButton control. Thank you for your help.
I'd suggest using a RadioButtonList:
Page Code
<asp:RadioButtonList RepeatLayout="UnorderedList" OnSelectedIndexChanged="IndexChanged" AutoPostBack="true" ID="RadioRepeater" runat="server" />
<asp:Label ID="SelectedRadioLabel" runat="server" />
Code Behind
if (!Page.IsPostBack)
{
/* example adds items manually
- you could iterate your datasource here as well */
this.RadioRepeater.Items.Add(new ListItem("Foo"));
this.RadioRepeater.Items.Add(new ListItem("Bar"));
this.RadioRepeater.Items.Add(new ListItem("Baz"));
this.RadioRepeater.SelectedIndex = this.RadioRepeater.Items.IndexOf(new ListItem("Bar"));
this.RadioRepeater.DataBind();
}
protected void IndexChanged(object sender, EventArgs e)
{
this.SelectedRadioLabel.Text = string.Format("Selected Item Text: {0}", this.RadioRepeater.SelectedItem.Text);
}
I assume you only need to select one item.
As described in the comments, it even works to access the SelectedItem in the Page_Loadevent handler:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
// previous code omitted
}
else
{
string foo = this.RadioRepeater.SelectedItem.Text;
}
}
If you are creating all your controls dynamically at run-time (directly from code), then things are a little different. Here is the code that I used:
Page Code
<form id="form1" runat="server">
</form>
Code Behind
protected void Page_Load(object sender, EventArgs e)
{
RadioButtonList rbl = new RadioButtonList();
rbl.AutoPostBack = true;
rbl.SelectedIndexChanged += rbl_SelectedIndexChanged;
rbl.Items.Add("All");
// generate your dynamic radio buttons here
for (int i = 0; i<5; i++)
{
rbl.Items.Add(string.Format("Dynamic{0}", i));
}
form1.Controls.Add(rbl);
if (!Page.IsPostBack)
{
rbl.SelectedValue = "All";
PopulateTextBox(rbl.SelectedValue);
}
}
void rbl_SelectedIndexChanged(object sender, EventArgs e)
{
RadioButtonList foo = (RadioButtonList)sender;
PopulateTextBox(foo.SelectedValue);
}
void PopulateTextBox(string selection)
{
TextBox box = new TextBox();
box.Text = selection;
form1.Controls.Add(box);
}
I have a repeater and inside it i have a checkbox. Now i want to check it according to columns value(0/1). I have tried it through the itemDataBound event of the repeater. what its doing if the rows has value 1 then its checked all checkbox and if first checkbox is unchecked then its unchecked all.
my code is:-
`
<td align="center">
<asp:CheckBox ID="chk" runat="server" />
</td>
</tr>
</ItemTemplate>
</asp:Repeater>`
The ItemDataBound events code is :-
protected void rp_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
DataTable dt = new DataTable();
dt = obj.abc(id);
if (dt.Rows.Count > 0)
{
CheckBox chk = (CheckBox)(e.Item.FindControl("chk"));
if (chk != null)
{
if (Convert.ToInt32(dt.Rows[0]["xyz"]) == Convert.ToInt32("0"))
{
chk.Checked = false;
}
else
{
chk.Checked = true;
}
}
}
}
There are many ways to do that.
You can write inline ASP.NET:
<asp:CheckBox id='isMarried' runat='server'
Checked='<%# Convert.ToBool(Eval("IsMarried")) ? true : false %>' />
As you have mentioned, you can use repeater_ItemDataBound to find the check-box of each row, and set its value accordingly:
protected void repeater_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
Person person = (Person)e.Item; // e.Item is the datasoruce of the row
if (person.IsMarried)
{
CheckBox isMarried = (CheckBox)(e.Item.FindControl("isMarried"));
isMarried.Checked = true;
}
}
Another way could be to inject the Boolean state (here, the marriage state) in a hidden field and send it to the client, then on client-side, using jQuery (or any other JavaScript framework), update check-boxes' checked state according to the value of those hidden fields:
I have a GridView with a DropDownList in each row. (The items in the DropDownList are the same for each.) I have a DropDownList "ddlView" outside of the GridView that is used for filtering the available options in the other DropDownLists. The default selection for ddlView is no filter.
When a user selects a new value for ddlView any selected values in the other DropDownLists disappear if they are not one of the values present after the filter is applied. What I would like to happen in that case is the previously selected value still be present and selected.
What is the best way to accomplish this?
The previously selected values are available during postback but appear to be cleared once DataBind() is called on the GridView, so I am unable to determine their previous value in the method where they are populated (the RowDataBound event).
My best idea so far is to manually store that information into an object or collection during postback and reference it later during the databinding events.
Is there a better way?
I don't think there is a better way to accomplish this as when the GridView is bound all of the controls are recreated thus removing the selections.
The following works: (I store the selections on postback to retrieve again in the RowDataBound event)
Markup
<asp:Button ID="button1" runat="server" Text="Post Back" OnClick="button1_Click" />
<br />
<asp:GridView ID="gridView1" runat="server">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:DropDownList ID="gridViewDropDownList" runat="server">
<asp:ListItem Value="1">Item 1</asp:ListItem>
<asp:ListItem Value="2">Item 2</asp:ListItem>
<asp:ListItem Value="3">Item 3</asp:ListItem>
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Code
public class GridViewDropDownSelections
{
public int RowIndex { get; set; }
public int SelectedIndex { get; set; }
}
...
private List<GridViewDropDownSelections> selectedDropDownListItems = new List<GridViewDropDownSelections>();
protected override void OnLoad(EventArgs e)
{
var selections = gridView1.Rows.Cast<GridViewRow>().Where(r => r.RowType == DataControlRowType.DataRow)
.Select(r => new GridViewDropDownSelections() { RowIndex = r.RowIndex, SelectedIndex = ((DropDownList)r.FindControl("gridViewDropDownList")).SelectedIndex }).ToList();
selectedDropDownListItems.AddRange(selections);
gridView1.RowDataBound += new GridViewRowEventHandler(gridView1_RowDataBound);
if (!IsPostBack)
{
BindDataGrid();
}
base.OnLoad(e);
}
protected void button1_Click(object sender, EventArgs e)
{
BindDataGrid();
}
private void BindDataGrid()
{
//Dummy data
string[] data = new string[] { "Item 1", "Item 2", "Item 3" };
gridView1.DataSource = data;
gridView1.DataBind();
}
void gridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
var selection = selectedDropDownListItems.FirstOrDefault(i => i.RowIndex == e.Row.RowIndex);
if (selection != null)
{
try
{
DropDownList gridViewDropDownList = (DropDownList)e.Row.FindControl("gridViewDropDownList");
gridViewDropDownList.SelectedIndex = selection.SelectedIndex;
}
catch (Exception)
{
}
}
}
}
Hope it helps.
Instead of using DataBinding to apply the filter, you could add/remove the DropdownList items through the Items property, when another filter is selected. This way the selected value in the dropdowns should not be resetted.
You might be able to accomplish this with a simple condition. I don't know how you're filtering the items, but it would go something like this:
for (int itemIndex = 0; itemIndex < DropDownList1.Items.Count; itemIndex++)
{
ListItem item = DropDownList1.Items[itemIndex];
if (DropDownList1.Items.IndexOf(item) > ddlView.SelectedIndex)
{
if (!item.Selected)
{
DropDownList1.Items.Remove(item);
}
}
}
Not sure if this is what you're looking for, but hope it helps.
Use client side javascript
Search for all the appropriate select inputs and for each one found, go through the options and remove the one selected in the master ddl
function UpdateDropDowns (tbl) {
var controls = tbl.getElementsByTagName('select');
for (var i = 0; i < controls.length; i++) {
RemoveOption(controls[i], 'the value to remove');
}
}
function RemoveOption(ddl, val)
{
for (var i = ddl.options.length; i>=0; i--) {
if (ddl.options[i].value == val) {
ddl.remove(i);
}
}
}
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.