Convert dataset into combobox items using LINQ - c#

I am trying to take a DataSet and add each item to a ComboBox.
I am currently using a foreach loop, like so:
foreach (DataRow row in ds.Tables[0].Rows)
{
cmbCauseForRepair.Items.Add(row[0].ToString() + ":" + row[1].ToString());
}
I would like to do this using LINQ.
Here is what I'm trying:
cmbCauseForRepair.Items.Add(from r in ds.Tables[0].Rows.Cast<DataRow>()
select r[0] + ":" + r[1]);
However, my ComboBox only has 1 item: "System.Linq.Enumerable".

LINQ isn't looping over the records for you. You still need to do that.
If cmbCauseForRepair.Items.Add() had an overload which accepted an enumeration of values then you wouldn't need to. But it doesn't. It just accepts an object. And according to that documentation, that object will be treated as:
A visual representation of the item is displayed in the combo box. This content representation is specified by the DisplayMember property. If the DisplayMember property is null, the item's ToString method is called to obtain the string that is displayed in the combo box; otherwise, the property of the stored object as specified by the DisplayMember property is displayed.
Since the object being passed to Add() is of type IEnumerable<string> then the .ToString() representation of it is:
`IEnumerable<string>`
Basically, you need to loop through your objects to add them one at a time:
var items = from r in ds.Tables[0].Rows.Cast<DataRow>()
select r[0] + ":" + r[1];
foreach (var item in items)
cmbCauseForRepair.Items.Add(item);
Or use a different method to add them:
cmbCauseForRepair.Items.AddRange(from r in ds.Tables[0].Rows.Cast<DataRow>()
select r[0] + ":" + r[1]);

.Add() only adds a single item.
Try the same approach, but use .AddRange(), which adds a collection of Objects to the ComboBox:
cmbCauseForRepair.Items.AddRange(from r in ds.Tables[0].Rows.Cast<DataRow>()
select r[0] + ":" + r[1]);

Better to use string.Format instead of concatenation string
cmbCauseForRepair.Items.AddRange(ds.Tables[0].Rows.Cast<DataRow>().Select(p => string.Format("{0}:{1}", p[0], p[1])).ToArray());

Related

How to take only first index from combobox c#

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";

Getting the value and items in checkListBox

I am writing a Windows Forms application that has a checkListBox. I have a databinded checkListBox value that is connected to my sql db. I want to write a loop to loop through a list of checked items and get its value (not index). I am wondering is there a way to do it just like the comboBox.SelectedValue?
foreach(var item in checkListBox.CheckedItems){
//get the value of that
string query = select * from employeeId where '"+checkListBox.SelectedValue+"'
}
You can try like this:
foreach(object item in checkListBox.CheckedItems)
{
DataRowView dt = item as DataRowView;
string str = dt["nameHere"];
// some code
}
You should cast the item to the relevant type (DataRowView?)
foreach(var item in checkListBox.CheckedItems){
var val = item as DataRowView;
// retrieving the relevant values
}
You can try this
foreach(var item in checkListBox.CheckedItems){
var value = (item as ListItem).Value;
}
The items in the CheckedListBox and checks every other item in the list. Using the Items property to get the CheckedListBox.ObjectCollection to get the Count of items.
Using the SetItemCheckState and SetItemChecked methods to set the check state of an item. For every other item that is to be checked, SetItemCheckState is called to set the CheckState to Indeterminate, while SetItemChecked is called on the other item to set the checked state to Checked.
//checkedListBox1.SetItemChecked(a,true);
for ( int i = 0; i < checkedListBox1.Items.Count; i++ )
{
if(checkedListBox1.GetItemCheckState(i) == CheckState.Checked)
{
string query = select * from employeeId where '" + checkedListBox1.Items[i].ToString() + "';
}
}
You can do it other way as well
List<object> _checkedItems = checkedListBox1.CheckedItems.OfType<object>().ToList();
This will give you all the checked items. If you want to pass this into sql query then you can do something like
string delimeter = "','";
string _selectedItems ="'"+ _checkedItems.Aggregate((i, j) => i + delimeter + j).ToString()+"'";
and pass it in your sql query
string query = select * from employeeId where somevalue in ("+_selectedItems +")

DataGrid - iterate over rows and access cell values of each row

In C# WPF I have a DataGrid-object. To fill the DataGrid-object with values I am setting the DataGrid.ItemsSource-property like this:
List<SomeClass> someClassList = new List<SomeClass>();
//adding elements to someClassList (omitted for brevity)
myDataGrid.ItemsSource = someClassList;
This works and I am able to see all the elements added to someClassList inside the DataGrid.
After the user clicks a button, I want to save all contents inside that DataGrid to an XML-file.
I thought it would therefore be clever to iterate over the rows of the DataGrid. With each iteration i could access the values inside the cells of one row at a time and write it to an XML-file.
To perform such an iteration I have written this code:
foreach (SomeClass someClassElement in myDataGrid.Items)
{
Trace.WriteLine("cell-A = " + someClassElement.propertyA +
"cell-B = " + someClassElement.propertyB +
"cell-C = " + someClassElement.propertyC);
}
Unfortunately executing it (by clicking a button) causes an InvalidCastException, although the WritLine-method is able to print every cell value into the Output-window.
How can I perform the iteration without an InvalidCastException ?
Is there a cleverer approach to save the DataGrid content to an XML-File ?
Iterate over myDataGrid.ItemsSource instead of myDataGrid.Items and you will get the SomeClass instances.

How to get value of checked item from CheckedListBox?

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(',');

How do I toggle the display for a dynamic id table?

I have a table that displays rows based on a drop down list option. The rows are dynamically created. I use the value on the ddl for the initial row, then a simple counter to make it unique. Is there a way to say something like show all the rows that start with "tableShoes" even though the rows are something like tableShoes1, tableShoes2, etc?
$('#itemSelect').change(function() {
var item = $('#itemSelect').val();
$('#itemList tr').each(function() {
$(this).hide();
});
$('#' + item + 'Header').show();
$('#' + item + '1').show();
//Because the table is dynamic, I am not sure how many
//rows would be available so I only see the first option.
});
I would suggest adding the same CSS class name to each row as it is added, perhaps the same as the value of the selected item. That way your last line could just be:
$('.' + item).show();
And you wouldn't have to worry about the index.
this selector shoud solve your problem: $('[id|=tableShoes]')

Categories

Resources