I have a dropdown which I fill with data from a SQL server.
I fill the dropdown dynamically in the Page_Init() Event.
Depending on the Value, a ListItem is selected.
Now the problem is, that when I select another Item in the dropdown, that after the postback the selection is reset to the first item in the dropdownlist.
This here is a basic version of my code which does not work:
ArrayList AD_Group_Members = ActiveDirectory.GetMemberOfGroup("AD-Group");
ArrayList ListMachines = SQLQuery.Read("Database", "SELECT idVM, RandomString, Computername, Owner, FROM VM ORDER BY Computername");
for (int i = 0; i < ListMachines.Count; i++)
{
String RandomString = ((Hashtable)ListMachines[i])["RandomString"].ToString();
String Owner = ((Hashtable)ListMachines[i])["Owner"].ToString();
DropDownList DropDownList_Owner = new DropDownList();
DropDownList_Owner.ID = "DropDownList_Owner_" + RandomString;
DropDownList_Owner.Width = Unit.Percentage(95);
DropDownList_Owner.AutoPostBack = true;
DropDownList_Owner.EnableViewState = true;
DropDownList_Owner.SelectedIndexChanged += DropDownList_Owner_SelectedIndexChanged;
Div_Test.Controls.Add(DropDownList_Owner);
for (int y = 0; y < AD_Group_Members.Count; y++)
{
ListItem ListItem = new ListItem();
ListItem.Value = Owner;
ListItem.Text = ((Hashtable)AD_Group_Members[y])["GivenName"].ToString() + " " + ((Hashtable)AD_Group_Members[y])["Surname"].ToString();
if (((Hashtable)AD_Group_Members[y])["Username"].ToString().Equals(Owner))
{
ListItem.Selected = true;
}
DropDownList_Owner.Items.Add(ListItem);
}
}
Where is the issue in my code, that it doesn't work but the example.
Thank in Advance
You have to populate your dropdownlist under this condition on pageload.
Because on every post back your ddl is populated again and loses its selected index.
if (!IsPostBack)
{
//PopulateYourDDL here
}
You filled dropdown in Page_Init() which gets called in every postback and refill your dropdown and hence loses selectedindex.So you have to fill your dropdown inside !ispostback block
if (!IsPostBack)
{
//fill your dropdown here
}
I think the you should have unique values for the dropdown. Also as you have duplicate values in data value field the problem is occurring. It is looking for the first match and selecting it. You could try to fabricate the values which you could uniquely identify. Something like below:
COLUMN_NAME DATA_TYPE
a a_decimal
b b_decimal
c c_decimal
d d_int
e e_int
f f_varchar
g g_varchar
h h_varchar
i i_varchar
j j_varchar
Check out this Useful Source!!!
I hope it helps!!! Have a close look at those comments in the accepted answer section !!!
Also avoid using SelectedIndex_Changed() functions while dealing with Dynamically generated Web controls. Bind the DropdownList under Page_Init() or Page_PreInit(). If you want to perform some functions upon DropDownlist Selection Check out this! to determine the WebControl ID which is triggered and then perform an unique function in the Page_PreInit() or Page_Init().
Related
dropdownlist always show the first index of Item populated from database and in debug mode ddlcountry.Text always empty string("").
I have "Philippines" item in my dropdownlist but "Argentina" always shown first in my dropdown instead of "Philippines".
Please help.
//in formload
if(!isPostback)
{
DataTable dtCountry= new DataTable();
dtCountry= network.GetCountry();
for (int row = 0; row < dtCountry.Rows.Count; row++)
{
ddlCoutry.Items.Add(new ListItem { Text = dtCountry.Rows[row][1].ToString(), Value = dtCountry.Rows[row][1].ToString() });
}
}
ddlCountry.Text = "Philippines";
As I mentioned in the comment above, I think your problem is you are trying to select the dropdown option by text but getting confused with .Text property. You can do this:-
ddlCountries.Items.FindByText("Philippines").Selected = true;
Set the selected item to "Philippines" because I assume your list of countries is in alphabetical order.
ddlCountry.SelectedIndex = ddlCountry.Items.IndexOf(ddlCountry.Items.FindByText("Philippines"));
Also I want to point out your variable is misspelled:
**ddlCoutry**.Items.Add(new ListItem { Text = dtCountry.Rows[row][1].ToString(), Value = dtCountry.Rows[row][1].ToString() });
I have a webpage with 4 dropdownlists on the page. In the page load method I have the code behind set the values of the dropdownlists. The problem is that when I set any one of the dropdownlists it sets all of the dropdownlists.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
//populating the dropdownlist with values
for (int i = 0; i < 60; i++)
{
ListItem temp = new ListItem(i + "");
ddl_EndMin.Items.Add(temp);
ddl_StartMin.Items.Add(temp);
if (i < 24)
{
ddl_EndHour.Items.Add(temp);
ddl_StartHour.Items.Add(temp);
}
}
//Setting the dropdownlists with the values from the conference variable
ddl_EndHour.SelectedIndex = conference.EndDate.Hour;
ddl_StartMin.SelectedIndex = conference.StartDate.Minute;
ddl_StartHour.SelectedIndex = conference.StartDate.Hour;
ddl_EndMin.SelectedIndex = conference.EndDate.Minute;
}
}
}
I'm not sure why setting one of these dropdownlists selected index sets all of them. I also tried replacing one of them with a ListBox and the value of the ListBox was set as well. There is code on another page that sets 2 dropdownlists using this selected index method but using states instead of numbers and that works just fine.
ddl_EndMin.SelectedIndex = ddl_EndMin.Items.IndexOf(ddl_EndMin.Items.FindByValue(conference.EndDate.Minute.ToString()));
ddl_EndHour.SelectedIndex = ddl_EndHour.Items.IndexOf(ddl_EndHour.Items.FindByValue(conference.EndDate.Hour.ToString()));
I tried copy/pasting that code into what I'm currently working on and changing the names and I got the same results. Any insight you can give me as to why this problem is occuring would be greatly appreciated.
At a guess it's because you're using the same item collection in all of your dropdowns.
Then when you set the selected property on one of the items it has that property in all of your lists as it's the same object reference in all lists.
What happens if you do this within the loop
ListItem temp = new ListItem(i + "");
ddl_EndMin.Items.Add(temp);
temp = new ListItem(i + "");
ddl_StartMin.Items.Add(temp);
if (i < 24)
{
temp = new ListItem(i + "");
ddl_EndHour.Items.Add(temp);
temp = new ListItem(i + "");
ddl_StartHour.Items.Add(temp);
}
Im having problems after postback in asp.net / c#. All radiobuttlists in gridview are cleared on postback (one radiobuttonlist on each row). So I save them to a Session variable.
But I cant set them back from the Session variable. Here is the code in page_load:
//.. testing for null,etc
for (int i = 0; i < lstRadioButtons.Count; i++)
{
RadioButtonList rbl = (RadioButtonList)gwTract.Rows[i].FindControl("RadioButtonList1");
rbl.SelectedItem.Value = lstRadioButtons[i]; //list with strings "0", etc
Debug.WriteLine("yep...");
}
Thanks in advance!
Assuming lstRadioButtons contains the value for a given row:
for (int itemIndex = 0; itemIndex < rbl.Items.Count; itemIndex++)
if (rbl.Items[i].Value == lstRadioButtons[i])
rbl.SelectedIndex = itemIndex;
Assuming lstRadioButtons contains the index for a given row:
rbl.SelectedIndex = int.Parse(i); //You may want to use TryParse to handle failure
I'm trying to find the selected Item in an aspx ListView that is on a separate page, then switch the page and select the item. I have the value property of the ListViewItem I am looking for, but cannot seem to get it to work. Here is what I tried:
for (int i = 0; i < lvProject.Items.Count; i++)
{
if (((Label)lvProject.Items[i].FindControl("Project_IDLabel")).Text == project.ToString())
{
lvProject.SelectItem(i);
break;
}
}
So lvProject is my list view. The project Variable is an Int64 which represents the UID of my Project. This is also the Value of my ListViewItems. The problem with the code above is that when paging is enabled, and the item is on a different page this will not work because the listView.Items.Count is set to the # of Items on the current page only.
My goal is to find the item, set the listview to display the correct page, and finally select the item. You would figure that I could just set the SelectedValue property, but this is not that simple as it is read only. Any ideas would help greatly, thanks in advance.
--Roman
In order to get the total record count from the object data source, you should use the Selected event as follows:
protected void ObjectDataSource1_Selected(object sender, ObjectDataSourceStatusEventArgs e)
{
// Get total count from the ObjectDataSource
DataTable dt = e.ReturnValue as DataTable;
if (dt != null) recordCount = dt.Rows.Count; // recordCount being declared outside the method
}
You would then be able to search for the item as follows:
for (int i = 0; i < recordCount; i++)
{
Label lblItem = (Label)lvProject.Items[i].FindControl("IdLabel");
if (lblItem.Text.Equals(itemToSearch))
{
lvProject.SelectedIndex = i;
break;
}
}
Hope it helps!
How do you bind ListView Items?
If you are using database level paging (stored procedure, query) - you should do search in the same way - using database query/stored procedure by passing a search criteria.
If you are bind ListView Items to a collection of items which are provided by a business/data layer - you have to create search method on layer which provides items so this method will be able to loop through the items.
You should set the SelectedIndex property to i
for (int i = 0; i < lvProject.Items.Count; i++)
{
if (((Label)lvProject.Items[i].FindControl("Project_IDLabel")).Text == project.ToString())
{
lvProject.SelectedIndex = i;
break;
}
}
My idea is to build a Ranking Priority using a DropDownList ASP server control.
Here's my setup: I have 3 DropDownLists and it has 3 items ("First", "Second", "Third") on each DropDownLists. When I have chosen the 1st DropDownList assuming the item I have selected is "First" and on the 2nd DropDownList by default its SelectedItem is "First" also the item of the 1st DropDownList on which I have selected must be swapped on the 2nd DropDownList.
In short there would be unique SelectedItems on each DropDownList and in every SelectedIndexChanged event occuring there would be swapping of items on the 3 DropDownLists. That's what my Ranking Priority would be.
My question would be, how can I swapped a previous item on the DropDownList going from one another DropDownList where I have selected on and placed a new item?
Here's my code:
protected void DropDownListPriority_SelectedIndexChanged(object sender, EventArgs e)
{
DropDownList ddlRank = (DropDownList)sender;
int swapIndex;
string sameDdlSelectedItemID;
//Get list of DDLs
List<DropDownList> ddlRankList = new List<DropDownList>();
ddlRankList.Add(ddlBiometricNoOrder);
ddlRankList.Add(ddlDateTimeOrder);
ddlRankList.Add(ddlTransactionTypeOrder);
//Store ListItems for DDL
List<string> strRankList = new List<string>();
strRankList.Add("First");
strRankList.Add("Second");
strRankList.Add("Third");
//Holds temp. DDL
List<DropDownList> tempRankList = new List<DropDownList>();
//Remove the '<-- Select -->' item when ddl is changed
if(ddlRank.Items.Contains(new ListItem("<-- Select -->")))
ddlRank.Items.RemoveAt(0);
//Loop on each List<T>
for(int x = 0; x < ddlRankList.Count; x++)
{
for (int y = 0; y < ddlRankList.ElementAt(x).Items.Count; y++)
{
if (ddlRankList.ElementAt(x).Items[y].Text != ddlRank.SelectedItem.Text)
{
//Check amongst the unselected item to be changed (int swapIndex)
swapIndex = Convert.ToInt32(ddlRankList.ElementAt(x).Items[y].Value);
}
}
}
foreach (DropDownList ddl in ddlRankList)
{
foreach (string strRank in strRankList)
{
if (ddlRank.SelectedItem.Text == ddl.SelectedItem.Text)
{
sameDdlSelectedItemID = ddl.ID;
//Set the ddl SelectedIndex
ddl.SelectedIndex = //This is my question;
}
}
}
}
I see that you have considered an approach where the lists are repopulated at server end. Is there any specific reason for it as server postbacks could be costly. Instead why don't you consider a jquery/javascript based solution where the lists are manipulated based on user selected values.
You can implement the event based model as well. Refer this