Adding values to DataGridViewComboBoxColumn with autocomplete - c#

I am new to using datagridviews and wanted to know how to populate certain fields.
I have created a form and added a datagridview (named GridSellProducts) with Visual Studio designer and added 8 columns with the first named Item.
I have also changed the column type for Item to DataGridViewComboBoxColumn also in design view.
I have the following data (product names) that I want to populate the combobox with for each row that may be added:
// get products
productsURL = "https://eko-app.com/Products/list_products/sessionId:" + sessionID + ".json";
var products = Products.GetProducts(productsURL);
List<string> productNames = new List<string>(); <-----the data to add to the combobox
foreach (var p in products)
{
var x = p.Product;
foreach (var pn in x)
{
productNames.Add(pn.name);
}
}
How do I add the above data to the column combobox Item that will let a user be able to type a product name and also have an autocomplete feature. I am using WinForms.

To populate your list with Items property in DataGridViewComboBoxColumn use this:
public DataGridViewComboBoxColumn cbColumn; // outside method for further use of inserting into DataBase
cbColumn = new DataGridViewComboBoxColumn();
bColumn.DataSource = productNames;
MSDN DataGridViewComboBoxColumn.DataSource Property

Related

Dynamically add data to columns in GridView

I have the following code that dynamically creates columns within a WPF GridView control, the header names come from a string[] which is stored in a List<string[]> named data_org
GridView gv = tabell.View as GridView;
foreach (string s in data_org.ElementAt(0))
{
gv.Columns.Add(new GridViewColumn { Header = s });
}
Is there a way to add data while I'm creating the columns? I've searched for ways of doing it in the add column statement but can't find a way.
gv.Columns.Add(new GridViewColumn{Header = s, **statement to add data to column**});
My data is stored in another List<float[]>, where each item float[] represents a column. Do I have to do something to handle that data type (float[]), too?
You do not add data items directly to the columns of a GridView. Instead, you set the ItemsSource of the associated ListView, which is tabell in your case.
tabell.ItemsSource = /* Set a binding or assign an items collection. */;
Then you would create bindings for each column to the corresponding properties on your data items that should be displayed in the columns using DisplayMemberBinding.
var gridViewColumn = new GridViewColumn
{
Header = s,
DisplayMemberBinding = new Binding(/* Binding property path / name of the property. */);
};
As you only have a list of floats for each column, you should create a suitable data item type first. The ItemsSource expects a list of items that contain properties for each column, it represents a row.
What you have to do now is:
Create a row data type that contains properties for each column
public class MyDataItem
{
public float Number { get; }
// ...properties for other columns..
}
Create a collection of these data items with data from you float lists.
var myDataItemList = new List<MyDataItem>();
// ...create data items, add your data and add the items to the list.
Assign the list as items source of the ListView.
tabell.ItemsSource = myDataItemList;
Add display member bindings for each column.
var gridViewColumn = new GridViewColumn
{
Header = s,
DisplayMemberBinding = new Binding(nameof(MyDataItem.Number));
};
Then it should work. However, I recommend you to have a look at the MVVM design pattern.

How to retrieve selected values for selected items in a ListBox?

I'm populating a ListBox in a WinForms application, this way:
listBoxUsers.DataSource = ctx.Users.ToList();
listBoxUsers.DisplayMember = "Name";
listBoxUsers.ValueMember = "Id";
how to retrieve the selected Ids when I'm setting the SelectionMode to MultiSimple
I want to do a foreach loop on them, like this:
foreach(var itemId in listBoxUsers.SelectedValues)//unfortunately not exist
{
int id = int.Parse(itemId);
// . . .
}
Since you know the type of items, you can use such code:
var selectedValues = listBox1.SelectedItems.Cast<User>().Select(x=>x.Id).ToList();
Side Note: The ListBox control lacks a GetItemValue method. A method which should work like GetItemText, but for getting values. In the linked post I shared an extension method to get the value from an item. Using that extension method you can get selected values independent from type of items:
var selectedValues = listBox1.SelectedItems.Cast<object>()
.Select(x => listBox1.GetItemValue(x)).ToList();
If for some reason you are interested to have a text representation for selected values:
var txt = string.Join(",", selectedValues);
Have you tried with the SelectedItems property?
foreach (var item in listBoxUsers.SelectedItems)
{
}
try this:
foreach (DataRowView item in listBoxUsers.SelectedItems)
{
int id=int.parse(item[0].ToString());
}

How to insert first item in combo box with text "SELECT" with default value 0 in C# windows application

I am using C# windows application. My code is as below
var categoryList = _objCategoryManager.GetAll();
cmbCategory.DisplayMember = "Name";
cmbCategory.ValueMember = "Id";
cmbCategory.DataSource = categoryList;
Here categoryList is of type IEnumerable. I want to insert item in ComboBox at 0 index i.e."--SELECT--"
You cannot insert item to your ComboBox after data binding. Instead insert the item in a copy of your data source before, then do the binding.
If categoryList is IEnumerable<T> and not a List<T> then you should copy it to a List<T> so that you can add your default value at the first index:
var categoryList = _objCategoryManager.GetAll().ToList();
categoryList.Insert(0, new Category {Id = -1, Name = "--SELECT--"});
Simply insert it into your list, so something like
var categoryList = _objCategoryManager.GetAll().ToList();
cmbCategory.DisplayMember = "Name";
cmbCategory.ValueMember = "Id";
categoryList.Insert(0, new Category() { Name = "--SELECT--"} );
cmbCategory.DataSource = categoryList;
categoryList.ToList().Find(o => o.ID == Convert.ToInt32(0)).Name = "--SELECT--";
Using LINQ, you can find the object you want to change (after binding) and modify that item.
Otherwise if you are adding an object into the list:
categoryList.ToList().Add(obj); // This should show the new item in the combo box
Ultimately your .GetAll() method should have returned the first one to be "--SELECT--" instead of trying to modify it afterwards.

Store elements from a ListView into a List

Since I haven't found anything that helped, I ask my question here:
I have a ListView where I select a whole row by click. Now I want to store these selected items into a List but don't know how this should work exactly.
List<String> itemSelected = new List<String>();
foreach (var selectedRow in listView1.SelectedItems)
{
itemSelected.Add(selectedRow);
}
That doesn't work because I need an index (selectedRow[?]) or something like that. How can I store the values of the first column when clicked the row?
EDIT: The problem is that the ListViewItems have the type "object"
The ListView gets populated this way:
using (SqlConnection connection = new SqlConnection(connectionQuery))
{
foreach (DataGridViewRow row in dataGridView1.SelectedRows)
{
col1 = row.Cells[col1.Text].Value.ToString();
col2 = row.Cells[col2.Text].Value.ToString();
col1Cells.Add(col1);
col2Cells.Add(col2);
}
}
You can do something like:
ListViewItem listViewItem = this.listView1.SelectedItems.Cast<ListViewItem>().FirstOrDefault();
if (listViewItem != null)
{
string firstColumn = listViewItem.Text;
string secondColumn = listViewItem.SubItems[0].Text;
// and so on with the SubItems
}
If you have more selected items and only need the values of the first columns you can use:
List<string> values = listView1.SelectedItems.Cast<ListViewItem>().Select(listViewItem => listViewItem.Text).ToList();
It's common to bind a ListView to the List of non-trivial types.
Then you can handle SelectedItemChanged or something like that. You receive the whole object (in type object) which you can cast to your custom type and retrieve any properties you want

Binding ListView to database

I have a problem with binding Listview to my database using Entity Framwork.
This code only shows the first row of the table but the records do not show:
var item = (from p in db.tbl_film
select p).FirstOrDefault();
string[] items = {item.flm_id.ToString(),item.flm_name,item.flm_description,item.flm_category };
foreach (var itemlist in items)
{
ListViewItem lvi = new ListViewItem(items);
listView1.Items.Add(lvi);
}
I have a table that has several records. Now I want to show it in the ListView.
Table: flm_film
Fields: flm_id, flm_name, flm_category
I want to see data with Entity Framework in ListView in details mode.
Consider this code :
var items = (from p in db.tbl_film select p).ToList();
foreach (var item in items)
{
// Create your ListViewItem here
// Then add it to your listView here.
}
If you want to retrieve multiple records, you shouldn't have to use FirstOrDefault() because, as it says, you get only the first record.

Categories

Resources