how to determine checkboxlist is checked/selected - - c#

when i execute the code i get 4 checkboxs and i checked/selected all 4 checkbox and when i try to debug the code, it does count that i have 4 checkbox but all 4 checkbox is selected=false.
what i am missing in code?
<asp:checkboxlist id="chk" runat="server" ondatabinding="chk_DataBinding"
ondatabound="chk_DataBound">
</asp:checkboxlist>
List<String> roles = new List<string>();
for (int i = 0; i < chk.Items.Count; i++)
{
if (chk.Items[i].Selected)
{
roles.Add(chk.Items[i].Value);
}
}

Your logic is consistent with the basic CheckBoxList given on the ListControl.Items page, and from personal experience, checking the .Selected property of the ListItem should work fine.
Check to make sure you aren't re-populating the CheckBoxList before you hit the "if checked" logic - if I had to guess, I'd say there's a good chance you're losing the list on every postback. The simple solution is don't call your databinding logic if it's a postback.

public string[] CheckboxListSelections(System.Web.UI.WebControls.CheckBoxList list)
{
ArrayList values = new ArrayList();
for(int counter = 0; counter < list.Items.Count; counter++)
{
if(list.Items[counter].Selected)
{
values.Add(list.Items[counter].Value);
}
}
return (String[]) values.ToArray( typeof( string ) );
}

Related

Find Multiple Selected ListView Item Indices in UWP App

I have a ListView named sandwichToppings which displays various sandwich toppings and allows the user to select multiple. In my controller code, I must capture the selected toppings by their index in the ListView, and send those indices back using an array.
The code which causes me to stumble is visible below. I have not been able to figure out the part which captures one or more toppings to the sandwich (the rest works fine).
void readSandwichSelection()
{
int[] toppings = null;
// One or many toppings were added to the sandwich.
if(toppingsAvailable.SelectedItems.Count > 0)
{
toppings = new int[toppingsAvailable.SelectedItems.Count];
int toppingIndex = 0;
for(int i = 0; i < toppingsAvailable.Items.Count; i++)
{
ListViewItem test = (ListViewItem)toppingsAvailable.Items.ElementAt(i);
if(test.IsSelected == true)
{
toppings[toppingIndex] = i;
toppingIndex++;
}
}
}
// No sandwich topping.
else
{
order.addSandwich(sandwichesAvailable.SelectedIndex + 1);
}
}
Along my journey, I have tried a couple solutions found on Telerik. The first:
foreach (ListViewDataItem item in radListView1.SelectedItems)
{
int example = radListView1.Items.IndexOf(item);
}
The above example fails to work because
ListViewDataItem does not exist.
When replaced by ListViewItem, a run-time error occurs: System.InvalidCastException: 'Unable to cast object of type 'System.String' to type 'Windows.UI.Xaml.Controls.ListViewItem'.'
The second attempted solution:
for (int i = 0; i < radListView1.Items.Count; i++)
{
if (this.radListView1.Items[i].Selected)
{
int example = i;
}
}
This solution cannot work because the .Selected property simply does not exist.
In all my hour of attempted work, I come up with either of these two problems. Either some form of cast exception occurs, or it is impossible to reach the property.
In my example above, I did have success in reaching the isSelected property by making a copy of each list item, and testing whether it had been selected. However, although Visual Studio lets me make the assignment
ListViewItem test = (ListViewItem)toppingsAvailable.Items.ElementAt(i);
this statement cannot run at compile time, causing an error as written previously. Which datatype other than ListViewItem must be used to count over list view items?
toppingsAvailable.SelectedItems will return a List<> of selected items. However, how could I know from this list which list index selected items belong to?
You can try the following code to get the selected toppings's indexes and put the indexes in an array. The indexes will be saved in the ToppingArray.
void readSandwichSelection()
{
int[] ToppingArray = new int[toppingsAvailable.SelectedItems.Count];
for (int i = 0; i < toppingsAvailable.SelectedItems.Count; i++)
{
var selectedIndex = toppingsAvailable.Items.IndexOf(toppingsAvailable.SelectedItems[i]);
ToppingArray[i] = selectedIndex;
}
}
Please try the following. It is Selected rather than IsSelected.
for (int i = 0; i < toppingsAvailable.Items.Count; i++)
{
var test = toppingsAvailable.Items[i];
if (test.Selected)
{
toppings[toppingIndex] = i;
toppingIndex++;
}
}

How to Remove an dropdown Item by finding Text

I am databinding my dropdown in the code behind as such
AttributeStatusDdl.Items.Clear();
AttributeStatusDdl.DataSource = StatusDs;
AttributeStatusDdl.DataTextField = "AttributeStatus";
AttributeStatusDdl.DataValueField = "AttributeStatus";
AttributeStatusDdl.DataBind();
Now I would like find any items which is a string 'Test' to be removed... How can i achieve this task..
I have tried using findByText but somehow not able to remove the items with text Test... Thank you in advance
myDropDown.Items.Remove(myDropDown.Items.FindByValue("Test"));
Your code should work, try this one
for(int i= AttributeStatusDdl.Items.Count -1; i>= 0; i--)
{
if (AttributeStatusDdl.Items[i].Text == "a")
AttributeStatusDdl.Items.RemoveAt(i);
}

DropDownList lose index after PostBack

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().

asp.net: How to manually (c#) select radiobutton in radiobuttonlist inside gridview from Session

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

Ranking Priority using DropDownList in C#

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

Categories

Resources