I found this code to take values from CheckedListBox with commas. But there is no Selected and Value definition for CheckedListBox object. (there are just 4 basic inheritances :Equals(), GetHashCode(), GetType(), ToString())
Which reference I need or how can I correct this error?
I put that image to show where it throws me error, here is the code:
string values = "";
for (int i = 0; i < clSiparisTipi.Items.Count; i++)
{
if (clSiparisTipi.Items[i].Selected)
{
values += clSiparisTipi.Items[i].Value + ",";
}
}
values = values.TrimEnd(',');
Edit: I also tried this code:
StringBuilder items = new StringBuilder();
foreach (var item in checkedListBox1.CheckedItems)
{
items.Append(item).Append(",");
}
MessageBox.Show(items.ToString().TrimEnd(','));
But for example when I chose two items from the list, giving me such result: System.Data.DataRowView,System.Data.DataRowView
CheckedListBox exposes a SelectedItems collection.
http://msdn.microsoft.com/en-us/library/system.windows.forms.listbox.selecteditems(v=vs.110).aspx
This in turn exposes a count and it's Item's are accessible via an index.
StringBuilder sb = new StringBuilder();
foreach(var item in clSiparisTipi.SelectedItems){
sb.Append((String)item.Value)
.Append(",");
}
// Remove trailing comma
sb.Remove(sb.Length-1,1);
string values = sb.ToString();
That should do the trick. Also be aware that concatenating strings is somewhat expensive. It's faster to use a StringBuilder whenever possible.
I solved my problem with this code (I guess I would mention about how do I populate items in my question)
StringBuilder items = new StringBuilder();
foreach (object checkedItem in clSiparisTipi.CheckedItems)
{
DataRowView dr = (DataRowView)checkedItem;
items.Append(dr["tanimId"]).Append(",");
}
MessageBox.Show(items.ToString().TrimEnd(','));
Once I done in this way..
var items = new StringBuilder();
foreach (Object ss in checkedListBox1.CheckedItems)
items.Append(string.Format("{0},",ss.ToString()));
Related
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 a small DataTable that contains a number of rows which I am running a LINQ query against.
I am having problems getting the LINQ to display the text that is in the datatable.
When I run it I can get the column name.
I have tried a number of different ways of doing it but to no avail.
Code as follows:
DataTable DTGetNarratives = DAL.GetNarrativeList();
var SelectedNarrative =
from n in DTGetNarratives.AsEnumerable()
where n.Field<string>("narr_code").Equals(ClsPublic.NarrativeCode)
select n;
foreach (var item in SelectedNarrative)
{
//test1.Add(item.Table.Columns[col].ToString());
//col++;
txtLine1.Text = item.Table.Columns[0].DefaultValue.ToString();
}
Any help on this would be great.
So you have one TextBox but an IEnumerable<DataRow>. Do you expect a single row? If not, how do you want to diplays multiple records on a single textbox?
You could comma separate them:
var allNarrCode = SelectedNarrative.Select(r => r.Field<string>("narr_code"));
txtLine1.text = string.Join(",", allNarrCode);
or as multiline TextBox use the Lines property:
txtLine1.Lines = allNarrCode.ToArray();
Only the first:
txtLine1.Text = SelectedNarrative.FirstOrDefault();
without LINQ:
foreach (DataRow row in SelectedNarrative)
{
string code = row.Field<string>("narr_code")
// the next line is pointless since you're overwriting the text on every row
//txtLine1.Text = code;
}
You can use the Field extension method like:
foreach (var item in SelectedNarrative)
{
txtLine1.Text = item.Field<string>("narr_code"); //here
}
(You can specify the column name in the method parameters)
I am not sure if you really need that since your TextBox would be populated with the last row's value.
To show all values in a single TextBox you can do:
txtLine1.Text = string.Join(" ",SelectedNarrative.Select(r=> r.Field<string>("narr_code")));
Or you can do
StringBuilder sb = new StringBuilder();
foreach (var item in SelectedNarrative)
{
sb.Append(item.Field<string>("narr_code"));
}
txtLine1.Text = sb.ToString();
I have a dataset called "results" with several rows of data. I'd like to get this data into a string, but I can't quite figure out how to do it. I'm using the below code:
string output = "";
foreach (DataRow rows in results.Tables[0].Rows)
{
output = output + rows.ToString() + "\n";
}
However, I think I'm missing something because this isn't working. Can someone point me in the right direction?
You need to specify which column of the datarow you want to pull data from.
Try the following:
StringBuilder output = new StringBuilder();
foreach (DataRow rows in results.Tables[0].Rows)
{
foreach (DataColumn col in results.Tables[0].Columns)
{
output.AppendFormat("{0} ", rows[col]);
}
output.AppendLine();
}
I've done this a lot myself. If you just need a comma separated list for all of row values you can do this:
StringBuilder sb = new StringBuilder();
foreach (DataRow row in results.Tables[0].Rows)
{
sb.AppendLine(string.Join(",", row.ItemArray));
}
A StringBuilder is the preferred method as string concatenation is significantly slower for large amounts of data.
You can get a columns value by doing this
rows["ColumnName"]
You will also have to cast to the appropriate type.
output += (string)rows["ColumnName"]
Your rows object holds an Item attribute where you can find the values for each of your columns. You can not expect the columns to concatenate themselves when you do a .ToString() on the row.
You should access each column from the row separately, use a for or a foreach to walk the array of columns.
Here, take a look at the class:
http://msdn.microsoft.com/en-us/library/system.data.datarow.aspx
I am trying to get a list of all elements from ListBox if no or one of items is selected or list of selected items if more than 1 are selected. I have written such a code but it doesn't compile :
ListBox.ObjectCollection listBoXElemetsCollection;
//loading of all/selected XMLs to the XPathDocList
if (listBoxXmlFilesReference.SelectedIndices.Count < 2)
{
listBoXElemetsCollection = new ListBox.ObjectCollection(listBoxXmlFilesReference);
}
else
{
listBoXElemetsCollection = new ListBox.SelectedObjectCollection(listBoxXmlFilesReference);
}
So for this piece of code to work I would need to use something like ListBox.SelectedObjectCollection listBoxSelectedElementsCollection; which I do not want because I would like to use it in such an foreach:
foreach (string fileName in listBoXElemetsCollection)
{
//...
}
I'd simply this a bit and not mess with the ListBox ObjectCollections if you don't need to. Since you want to iterate items on your ListBox as strings, why not use a List and load the list how you show:
List<string> listItems;
if (listBoxXmlFilesReference.SelectedIndices.Count < 2) {
listItems = listBoxXmlFilesReference.Items.Cast<string>().ToList();
} else {
listItems = listBoxXmlFilesReference.SelectedItems.Cast<string>().ToList();
}
foreach (string filename in listItems) {
// ..
}
You need to convert SelectedObjectCollection to an array of object[].
ListBox.SelectedObjectCollection sel = new
ListBox.SelectedObjectCollection(listBoxXmlFilesReference);
ListBox.ObjectCollection col = new
ListBox.ObjectCollection(listBoxXmlFilesReference,
sel.OfType<object>().ToArray());
I can see what you're trying to do and it doesnt compile because the type ListBox.ObjectCollection is not the same as ListBox.SelectedObjectCollection - even though in your case they are lists that contain strings the classes themselves are different hence the compile error.
Assuming your items are strings in the listbox you could do:
var items = listBoXElemetsCollection.Items.OfType<string>();
if (listBoXElemetsCollection .SelectedIndices.Count >= 2)
items = listBoXElemetsCollection.SelectedItems.OfType<string>();
foreach(var item in items)
//do stuff
I have used a CheckedListBox over my WinForm in C#. I have bounded this control as shown below -
chlCompanies.DataSource = dsCompanies.Tables[0];
chlCompanies.DisplayMember = "CompanyName";
chlCompanies.ValueMember = "ID";
I can get the indices of checked items, but how can i get checked item text and value. Rather how can i enumerate through CheckedItems accessing Text and Value?
Thanks for sharing your time.
Cast it back to its original type, which will be a DataRowView if you're binding a table, and you can then get the Id and Text from the appropriate columns:
foreach(object itemChecked in checkedListBox1.CheckedItems)
{
DataRowView castedItem = itemChecked as DataRowView;
string comapnyName = castedItem["CompanyName"];
int? id = castedItem["ID"];
}
EDIT: I realized a little late that it was bound to a DataTable. In that case the idea is the same, and you can cast to a DataRowView then take its Row property to get a DataRow if you want to work with that class.
foreach (var item in checkedListBox1.CheckedItems)
{
var row = (item as DataRowView).Row;
MessageBox.Show(row["ID"] + ": " + row["CompanyName"]);
}
You would need to cast or parse the items to their strongly typed equivalents, or use the System.Data.DataSetExtensions namespace to use the DataRowExtensions.Field method demonstrated below:
foreach (var item in checkedListBox1.CheckedItems)
{
var row = (item as DataRowView).Row;
int id = row.Field<int>("ID");
string name = row.Field<string>("CompanyName");
MessageBox.Show(id + ": " + name);
}
You need to cast the item to access the properties of your class.
foreach (var item in checkedListBox1.CheckedItems)
{
var company = (Company)item;
MessageBox.Show(company.Id + ": " + company.CompanyName);
}
Alternately, you could use the OfType extension method to get strongly typed results back without explicitly casting within the loop:
foreach (var item in checkedListBox1.CheckedItems.OfType<Company>())
{
MessageBox.Show(item.Id + ": " + item.CompanyName);
}
You can iterate over the CheckedItems property:
foreach(object itemChecked in checkedListBox1.CheckedItems)
{
MyCompanyClass company = (MyCompanyClass)itemChecked;
MessageBox.Show("ID: \"" + company.ID.ToString());
}
http://msdn.microsoft.com/en-us/library/system.windows.forms.checkedlistbox.checkeditems.aspx
foreach (int x in chklstTerms.CheckedIndices)
{
chklstTerms.SelectedIndex=x;
termids.Add(chklstTerms.SelectedValue.ToString());
}
To get the all selected Items in a CheckedListBox try this:
In this case ths value is a String but it's run with other type of Object:
for (int i = 0; i < myCheckedListBox.Items.Count; i++)
{
if (myCheckedListBox.GetItemChecked(i) == true)
{
MessageBox.Show("This is the value of ceckhed Item " + myCheckedListBox.Items[i].ToString());
}
}
Egypt Development Blog : Get value of checked item in CheckedListBox in vb.net
after bind CheckedListBox with data you can get value of checked items
For i As Integer = 0 To CheckedListBox1.CheckedItems.Count - 1
Dim XDRV As DataRowView = CType(CheckedListBox1.CheckedItems(i), DataRowView)
Dim XDR As DataRow = XDRV.Row
Dim XDisplayMember As String = XDR(CheckedListBox1.DisplayMember).ToString()
Dim XValueMember As String = XDR(CheckedListBox1.ValueMember).ToString()
MsgBox("DisplayMember : " & XDisplayMember & " - ValueMember : " & XValueMember )
Next
now you can use the value or Display of checked items in CheckedListBox from the 2 variable XDisplayMember And XValueMember in the loop
hope to be useful.
I've already posted GetItemValue extension method in this post
Get the value for a listbox item by
index. This extension
method will work for all ListControl classes including
CheckedListBox, ListBox and ComboBox.
None of the existing answers are general enough, but there is a general solution for the problem.
In all cases, the underlying Value of an item should be calculated regarding to ValueMember, regardless of the type of data source.
The data source of the CheckedListBox may be a DataTable or it may be a list which contains objects, like a List<T>, so the items of a CheckedListBox control may be DataRowView, Complex Objects, Anonymous types, primary types and other types.
GetItemValue Extension Method
We need a GetItemValue which works similar to GetItemText, but return an object, the underlying value of an item, regardless of the type of object you added as item.
We can create GetItemValue extension method to get item value which works like GetItemText:
using System;
using System.Windows.Forms;
using System.ComponentModel;
public static class ListControlExtensions
{
public static object GetItemValue(this ListControl list, object item)
{
if (item == null)
throw new ArgumentNullException("item");
if (string.IsNullOrEmpty(list.ValueMember))
return item;
var property = TypeDescriptor.GetProperties(item)[list.ValueMember];
if (property == null)
throw new ArgumentException(
string.Format("item doesn't contain '{0}' property or column.",
list.ValueMember));
return property.GetValue(item);
}
}
Using above method you don't need to worry about settings of ListBox and it will return expected Value for an item. It works with List<T>, Array, ArrayList, DataTable, List of Anonymous Types, list of primary types and all other lists which you can use as data source. Here is an example of usage:
//Gets underlying value at index 2 based on settings
this.checkedListBox.GetItemValue(this.checkedListBox.Items[2]);
Since we created the GetItemValue method as an extension method, when you want to use the method, don't forget to include the namespace in which you put the class.
This method is applicable on ComboBox and CheckedListBox too.
try:
foreach (var item in chlCompanies.CheckedItems){
item.Value //ID
item.Text //CompanyName
}
You may try this :
string s = "";
foreach(DataRowView drv in checkedListBox1.CheckedItems)
{
s += drv[0].ToString()+",";
}
s=s.TrimEnd(',');