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
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 am using CheckedListBox so that user can multi select items for this i am populating CheckedListBox dynamically from database Here is CheckedListBox Filling Method
public void FillSubjectsCombo()
{
DataTable dt = objSubCls.FillSubjects();
chkLstBxClass_FrmSubjecClassRelation.DataSource = dt;
chkLstBxClass_FrmSubjecClassRelation.DisplayMember = "Subjects";
chkLstBxClass_FrmSubjecClassRelation.ValueMember = "SubId";
chkLstBxClass_FrmSubjecClassRelation.Enabled = true;
for (int i = 0; i < dt.Rows.Count; i++)
{
//Here i am setting Every item Checked
chkLstBxClass_FrmSubjecClassRelation.SetItemCheckState(i, CheckState.Checked);
}
}
On the Same Windows Form I have DataGridView i Want when i double click any row of datagrid then from selected row get value and from that value make respected item checked in CheckedListBox and other item UnChecked
Here is the DataGridView Event
private void dgv_FrmSubjectClassRelation_CellContentDoubleClick(object sender, DataGridViewCellEventArgs e)
{
string classId = dgv_FrmSubjectClassRelation.CurrentRow.Cells[3].Value.ToString();
string className = dgv_FrmSubjectClassRelation.CurrentRow.Cells[4].Value.ToString();
foreach (int i in chkLstBxClass_FrmSubjecClassRelation.CheckedIndices)
{
//Here I am UnChecking Every Checked Item
chkLstBxClass_FrmSubjecClassRelation.SetItemCheckState(i, CheckState.Unchecked);
}
My Question : How to Checked The Specific Item When Double Clicking DataGridView
Update: I am binding My DataGridView Like This
for (int i = 0; i < dt.Rows.Count; i++)
{
dgv_FrmSmstrClsAssign.Rows.Add();
dgv_FrmSmstrClsAssign.Rows[i].Cells[0].Value = dt.Rows[i].ItemArray[0];//Acadmc Yr
dgv_FrmSmstrClsAssign.Rows[i].Cells[1].Value = dt.Rows[i].ItemArray[1];// Semester Name
dgv_FrmSmstrClsAssign.Rows[i].Cells[2].Value = dt.Rows[i].ItemArray[2]; //College
dgv_FrmSmstrClsAssign.Rows[i].Cells[3].Value = dt.Rows[i].ItemArray[3];//Class
dgv_FrmSmstrClsAssign.Rows[i].Cells[4].Value = dt.Rows[i].ItemArray[4]; //Entry Date
dgv_FrmSmstrClsAssign.Rows[i].Cells[5].Value = dt.Rows[i].ItemArray[5];//IsActive
dgv_FrmSmstrClsAssign.Rows[i].Cells[6].Value = dt.Rows[i].ItemArray[6];//AcadmicYr Id
dgv_FrmSmstrClsAssign.Rows[i].Cells[7].Value = dt.Rows[i].ItemArray[7];//Semster Id
dgv_FrmSmstrClsAssign.Rows[i].Cells[8].Value = dt.Rows[i].ItemArray[8];//Semster Id
}
I was unable to find any method that allows you to easily map the bound value, so you will have to use IndexOf method of Items collection to obtain the index and then manually check-uncheck the items.
To obtain the bound item from DataGridView row you can use DataGridViewRow.DataBoundItem property:
private void CheckSelectedItem()
{
// Get bound item object from datagrid
object item = dgv_FrmSubjectClassRelation.CurrentRow.DataBoundItem;
// Get corresponding index in listView
Int32 itemIndexInCheckedListView = chkLstBxClass_FrmSubjecClassRelation.Items.IndexOf(item);
// Check the item in listView
chkLstBxClass_FrmSubjecClassRelation.SetItemCheckState(itemIndexInCheckedListView,
CheckState.Checked);
}
private void dgv_FrmSubjectClassRelation_CellContentDoubleClick(object sender, DataGridViewCellEventArgs e)
{
string classId = dgv_FrmSubjectClassRelation.CurrentRow.Cells[3].Value.ToString();
string className = dgv_FrmSubjectClassRelation.CurrentRow.Cells[4].Value.ToString();
foreach (int i in chkLstBxClass_FrmSubjecClassRelation.CheckedIndices)
{
//Here I am UnChecking Every Checked Item
chkLstBxClass_FrmSubjecClassRelation.SetItemCheckState(i, CheckState.Unchecked);
}
// --------------Check the selected item----------------
this.CheckSelectedItem();
}
EDIT:
What you do is not exactly binding (well, it is binding, just not as Windows Forms defines it), so the previous solution won't work for you. If both your DataTable and DataGridView contain primary key or another unique identifier, then it is possible to map CurrentRow to the Item in DataTable:
private void CheckSelectedItem()
{
// Get bound item object from datagrid
object uniqueKey = dgv_FrmSubjectClassRelation.
CurrentRow.
Cells["SOME UNIQUE VALUE COLUMN"].
Value;
// Adapting http://stackoverflow.com/a/9300237/3745022 - there are more simple LINQless
// solutions for this situation, but it is not important for the concept.
Int32 itemIndexInCheckedListView = chkLstBxClass_FrmSubjecClassRelation.
Items.
Select((value, index) => new { value, index }).
Where(pair => pair.value.UniqueValue == uniqueKey ).
Select(pair => pair.index + 1).
FirstOrDefault() - 1;
// Check the item in listView
chkLstBxClass_FrmSubjecClassRelation.SetItemCheckState(itemIndexInCheckedListView,
CheckState.Checked);
}
If you do not have such Unique column you may want to add it(just make it hidden)
OR even better - use full-blown DataBinding - http://msdn.microsoft.com/en-us/library/fbk67b6z(v=vs.90).aspx;
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().
I have two list boxes in my form. I bound some data in the first list box. Now I have to select the items from the first lis tbox and should bind those selected items to the second list box when I press the button which is between these two list boxes. I am able to bind a single item at a time but I am having problem binding multiple selected items.
I am using the following code:
Hashtable ht = new Hashtable();
ht.Add(lbCATallSubcat.SelectedValue.ToString(),lbCATallSubcat.Text.ToString());
int i = 0;
foreach (string ent in ht.Values) {
string[] name = new string[lbCATallSubcat.Items.Count];
for (i = 0; i < lbCATallSubcat.SelectedItems.Count; i++) {
name[i] = lbCATallSubcat.Text;
this.lbCATSelectedSubcat.Items.Add(name[i]);
}
lbCATSelectedSubcat.DisplayMember = ht.Values.ToString();
lbCATSelectedSubcat.ValueMember = ht.Keys.ToString();
}
I have a datalist in have I have checkbox, I am selecting the checkbox in client side using jquery, based on that checkbox selection I am deleting the item, few Item is not getting deleted as there is an instance in some other table, the items which is not deleted I want to show checkbox as check and error msg show that Selected item can't be deleted.
after deleting the item I am getting the not deleted Item ID but how to again check the checkbox based on that id.
on deleted btn
foreach (DataListItem dl in dltlist1.Items)
{
if ((((CheckBox)dl.FindControl("Chkbox")).Checked))
{
ImageButton img = (dl.FindControl("btn1") as ImageButton);
string[] str = img.CommandArgument.ToString().Split(';');
Id = Convert.ToInt32(str[0]);
IdList.Add(Id);
}
}
List<Tuple<int, int>> x = objBAL.Delete(IdList);
Tuple<int, int> temp = new Tuple<int, int>(item.Key, 1); // I am getting here non deleted key
after deleting the item I am binding the datalist again.
plz some one help me how to do that?
After rebinding the DataList you can loop through the DataList items and match the non deleted keys with the DataKey and if you find a match you can recheck the Checkbox.
Example:
//here ArrayList contains the ids to match
ArrayList a=new ArrayList();
a.Add(201105);
a.Add(201106);
//loop through the items in the datalist
for (int i = 0; i < DataList1.Items.Count;i++ )
{
//check if the list contains the items
if (a.Contains(Convert.ToInt32(DataList1.DataKeys[i])))
{
(DataList1.Items[i].FindControl("CheckBox1") as CheckBox).Checked = true;
}
}
Any collection or generic that has .Contains() method would be ideal for this.
hope this helps.