I am having an issue getting the checkedlistbox to display all selections in a message box for a windows application. I am only getting the last one selected to display. For example, I select "one, three, and five", only five displays.
Here is my code:
string display = "";
foreach (object selectedItems in clb.CheckedItems)
{
if (clb.SelectedItems.Count != 0)
{
display = "Items needed\n-----------\n\n\n" + selectedItems.ToString();
}
else
{
display = "No items selected";
}
}
MessageBox.Show(display, "Title");
Any ideas to point me in the right direction to accomplish this is appreciated.
Your error is in the loop that starts before the test of the number of items selected/checked. Your loop continues changing the value of the variable display at each loop. At the end the variable contains only the last item checked/selectd.
So, I assume that you want to display the checkeditems, not the selecteditems.
In any case you need to loop over the collection (ChekedItems in this case) and accumulate in a stringbuilder the item texts that you want to display.
string display = "";
// Every item in this collection is an item
// with CheckState = Checked or Indeterminate
if (clb.CheckedItems.Count != 0)
{
StringBuilder sb = new StringBuilder();
foreach(string item in clb.CheckedItems)
sb.AppendLine(item);
display = "Items needed\n-----------\n\n\n" + sb.ToString();
}
else
{
display = "No items checked";
}
MessageBox.Show(display, "Title");
If you really want to loop on the selecteditems, the code is the same, but just use the SelectedItems collection
you need to concat the selected items like display += or better to use Stringbuilder
display += " Items needed\n-----------\n\n\n" + selectedItems.ToString();
OR you can do as below
if(clb.CheckedItems.Count >0)
display = "Items needed\n-----------\n\n\n" + string.Join(",", clb.CheckedItems.Select( i=>i.ToString()));
else
display = "No items selected";
Related
I have two indexes on my combobox.
I want to take only the first index ?
Can I get some example ?
The code:
foreach (DataRow dr2 in dt2.Rows)
{
comboBox1.Items.Add(dr2["Station"].ToString() + " - " + dr2["Ime"].ToString());
}
I want to take dr2["Station"].ToString() ?
The Win Forms ComboBox has both a SelectedIndex and SelectedText property.
Once your list is loaded with items you can pick which one is selected like this:
// selected by position in the list
comboBox1.SelectedIndex = 0;
// ... by value
comboBox1.SelectedText = "some value";
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();
I have two listboxes when i swap value to another listbox it always remove next value from the list and when i try to swap last value from the list it take top one value form the list . I try to find the problem but i don't get any result. Below is the code part for review.
private void MoveListBoxItems(ListBox lstEmployeelist, ListBox lstSelectedEmployees)
{
ListBox.SelectedObjectCollection sourceItems = lstEmployeelist.SelectedItems;
List<Master> newsource = this.masterBindingSource.DataSource as List<Master>;
List<Master> _selectedSource = this.masterSellectedBindingSource.DataSource as List<Master>;
try
{
if (lstEmployeelist.Items.Count > 0)
{
for (int i = 0; i <= sourceItems.Count -1 ; i++)
{
Master item = sourceItems[i] as Master;
this.masterSellectedBindingSource.AddNew();
Master sitems = masterSellectedBindingSource.Current as Master;
sitems.Empno = item.Empno;
sitems.FirstName = item.FirstName;
newsource.Remove((Master)item);
}
if (sourceItems.Count > 0)
this.masterBindingSource.RemoveCurrent();
this.masterSellectedBindingSource.EndEdit();
lstSelectedEmployees.DataSource = masterSellectedBindingSource;
lstSelectedEmployees.DisplayMember = "FirstName";
lstSelectedEmployees.ValueMember = "Empno";
}
}
catch (Exception ex)
{
throw ex;
}
}
I believe the problem is with the way you iterate through sourceItems.
Because you are doing it using a for loop (presumably because you cannot do it with a foreach because you cant then modify the collection), when you remove say item 1 from the collection and add it to the 2nd list, item 2 and all items after move up 1.
So item 2 becomes the new item 1 and item 3 becomes item 2, etc, etc...
To fix this, when you decide to move an item you also need to decrease i by 1 (i--;) so that when the for loops round again and i is increased it is back to the same index.
IF you are moving ALL items and not only select items, then you should not use a for loop, use a while instead like this:
while (sourceItems.Count > 0)
{
// code here
}
I have user submitted content that is loaded into c# winform in our office for processing before officially added to database. The user can submit a 'Referrer' as two text fields-first and last name. In the office I want to have a combobox will all existing referrers loaded in, then the first couple letters of the name to advance the combobox down to the area it needs to be at. I want to do something like this, taking the first two letters of the name and use that to initialize the combobox.
if (txtrefFirstName.TextLength > 2)
{
string firstStart = "" + txtrefFirstName.Text[0] + txtrefFirstName.Text[1];
firstStart = firstStart.ToUpper();
ddlReferring.SelectedText.StartsWith(firstStart);
}
else
ddlReferring.Text = "";
Any ideas or suggestions to get this to work?
Thanks
David K.
You could write something like this...
foreach (string item in ddlReferring.Items)
{
if (item.StartsWith(firstStart))
{
ddlReferring.SelectedText = item;
break;
}
}
Assuming the ddl's datasource is a List of String objects, you should be able to do some comparison on the datasource itself. I tend to use Linq for things like this but it isn't strictly necessary, just shorter.
if (txtrefFirstName.TextLength > 2)
{
string firstStart = txtrefFirstName.Text.Substring(0,2).ToUpper();
string Selection = ddlReferring.DataSource.Where(a=>a.StartsWith(firstStart)).FirstOrDefault();
ddlReferring.SelectedText = Selection ?? "";
}
else
ddlReferring.Text = "";
The selection line can also come from the items collection directly
string Selection = ddlReferring.Items.OfType<string>().Where(a=>a.StartsWith(firstStart)).FirstOrDefault();
Or if you REALLY dont want to use Linq...
string Selection = "";
foreach (object item in ddlReferring.Items)
if (item.ToString().StartsWith(firstStart))
{
Selection = item.ToString();
break;
}
Similar methods can be used even if the ddl's data is not a list of strings, just make sure to cast the items appropriately and compare the correct values.
I have quite a few radiobuttonLists in my ASP.net webform. I am dynamically binding them using the method shown below:
public static void PopulateRadioButtonList(DataTable currentDt, RadioButtonList currentRadioButtonList, string strTxtField, string txtValueField,
string txtDisplay)
{
currentRadioButtonList.Items.Clear();
ListItem item = new ListItem();
currentRadioButtonList.Items.Add(item);
if (currentDt.Rows.Count > 0)
{
currentRadioButtonList.DataSource = currentDt;
currentRadioButtonList.DataTextField = strTxtField;
currentRadioButtonList.DataValueField = txtValueField;
currentRadioButtonList.DataBind();
}
else
{
currentRadioButtonList.Items.Clear();
}
}
Now, I want to Display only the first Letter of the DataTextField for the RadioButton Item Text.
For example if the Value is Good I just want to Display G. If it Fair I want to display F.
How do I do this in C#
Thanks
You can't do what you want when you do the binding, so you have 2 options:
Modify the data you get from the table, before you do the binding.
After binding, go through each item and modify its Text field.
So, it you want to display "only the first Letter of the DataTextField for the RadioButton Item Text", you can do:
currentRadioButtonList.DataSource = currentDt;
currentRadioButtonList.DataTextField = strTxtField;
currentRadioButtonList.DataValueField = txtValueField;
currentRadioButtonList.DataBind();
foreach (ListItem item in currentRadioButtonList.Items)
item.Text = item.Text.Substring(0, 1);
If I misunderstood you and you want to display the first letter of the Value field, you can replace the last two lines with:
foreach (ListItem item in currentRadioButtonList.Items)
item.Text = item.Value.Substring(0, 1);
You could add a property to the type that is being bound (the one that contains Good, Fair, etc.) and bind to this property. If you will always be using the first letter, you could make it like so (adding in null checks, of course):
public string MyVar { get; set; }
public string MyVarFirstChar
{
get { return MyVar.Substring(0, 2); }
}