binding selected items from one list box to another listbox - c#

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();
}

Related

Dynamically add SubMenuItems to a SubMenu

I have a c# menu strip with top-level menu items (TLM items). I am dynamically adding items to one of the TLM items as follows, which works great.
DataRowCollection DRC = DataAccessClass.GetData("SELECT * FROM company ORDER BY CompanyName");
ToolStripMenuItem[] items = new ToolStripMenuItem[DRC.Count];
int itemCounter = 0;
foreach (DataRow dr in DRC)
{
string nm = dr["companyname"].ToString();
int id = Convert.ToInt16(dr["companyid"].ToString());
items[itemCounter] = new ToolStripMenuItem();
items[itemCounter].Name = string.Format("menuitem{0}", itemCounter);
items[itemCounter].Text = nm;
items[itemCounter].Click += new EventHandler(MenuItemClickHandler);
itemCounter++;
}
CompanyToolStripMenuItem.DropDownItems.AddRange(items);
Once this TLM has been populated, I want to dynamically add sub-menu items to each of the dynamic menu items created above. I am similarly creating an array of ToolStripMenuItems as above, and I am trying to add them to a menu item using this, shown here for the first menu item:
CompanyToolStripMenuItem.DropDownItems[0].DropDownItems.AddRange(submenuitems);
But it isn't working. Any ideas?
When I add CompanyToolStripMenuItem.DropDownItems[0] to a watch window, it is showing a "DropDownItems" property. When I try to type it in, the auto-complete drop-down isn't exposing the property as an option.
Try casting the selected DropDownItem item to a ToolStripMenuItem:
((ToolStripMenuItem)CompanyToolStripMenuItem.
DropDownItems[0]).DropDownItems.AddRange(submenuitems);

How to Add Items From One ListView to Another

I am trying to parse the data in the first column of one ListView called raw and then if the data is correct, add that item to a second ListView called result.
However, when I go to run my program I get
the error:
"Cannot add or insert the item 'Collected' in more than one place.".
My Code
ListView result = new ListView();
for (int i = 0; i < raw.Items.Count; i++)
{
if (raw.Items[i].SubItems[0].Text.ToUpper() == "COLLECTED")
{
MessageBox.Show("confirm");
result.Items.Add(raw.Items[i]); // generating erros
}
}
printUsingLView(result);
clone original item:
result.Items.Add((ListViewItem)raw.Items[i].Clone());
or, if you want to make some adjustments
ListViewItem newItem = new ListViewItem();
newItem.Text = raw.Items[i].Text;
//enter other properties here and then add it to new listView
result.Items.Add(newItem);

Writing data from multiple list box into excel columns in c#

I have a windows form application in c# where there are list of data in multiple listbox (around 56 in each listbox).
here is an example:
listbox1 contains data of name of students
listbox2 contains data of address of students
listbox3 contains percentage of students.
the list goes on with the student data.
Now i need to print the data in excel in a button click event.
the data should go in an ordered way .
I tried using the CSV helper but it only helped me for 1 set of list box i need to sent data from multiple list box.
var sw = new StreamWriter(#"output.csv");
var csvWriter = new CsvHelper.CsvWriter(sw);
foreach (var Name in lbx.Items)
{
csvWriter.WriteField(Name);
csvWriter.NextRecord();
}
foreach (var Address in ptr.Items)
{
csvWriter.WriteField(Address);
}
sw.Flush();
However, this doesn't solve the problem. Any help regarding the solution to this problem would be helpful.
Any other method to solve the problem will be great.
It's difficult for me to determine the full details of your configuration, but if it's as simple as two ListBox controls for which you're writing values, you could easily do something like the following:
var sw = new StreamWriter(#"output.csv");
var csvWriter = new CsvHelper.CsvWriter(sw);
int lbxCount = lbx.Items.Count;
int ptrCount = ptr.Items.Count;
for (int i = 0; i < Math.Max(lbx.Items.Count, ptr.Items.Count); i++)
{
object lbxValue = lbxCount > i ? lbx.Items[i] : String.Empty;
object ptrValue = ptrCount > i ? ptr.Items[i] : String.Empty;
csvWriter.WriteField(lbxValue);
csvWriter.WriteField(ptrValue);
csvWriter.NextRecord();
}
sw.Flush();
sw.Close();
This determines the maximum number of records to write (Math.Max(lbx.Items.Count, ptr.Items.Count) based on the greatest ListBox.Items.Count.
By altering your loops to be a single loop, you can now use the WriteField method correctly. If the ListBox lbx does not contain a value for a certain record, it uses a String.Empty as the value for that record. Likewise it does the same for ListBox ptr, in the event that there are more items in lbx.
If you have many ListBox controls on a single form and wish to each of them, you could determine the maximum items overall by iterating through all ListBox controls and getting their respective Item.Count values as follows:
var sw = new StreamWriter(#"output.csv");
var csvWriter = new CsvHelper.CsvWriter(sw);
int maxRecords = 0;
List<ListBox> listBoxes = new List<ListBox>();
// Add all ListBox controls to list
// Determine maximum number of items (in all ListBox controls)
foreach (Control control in Controls)
{
if (control.GetType() == typeof(ListBox))
{
ListBox currentListBox = (ListBox)control;
listBoxes.Add(currentListBox);
if (currentListBox.Items.Count > maxRecords)
maxRecords = currentListBox.Items.Count;
}
}
// Write fields for each ListBox
for (int i = 0; i < maxRecords; i++)
{
foreach (ListBox currentListBox in listBoxes)
{
if (currentListBox.Items.Count > i)
csvWriter.WriteField(currentListBox.Items[i]);
else
csvWriter.WriteField(String.Empty);
}
csvWriter.NextRecord();
}
sw.Flush();
sw.Close();

How to again recheck the checkbox after deleting some item on btn click?

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.

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