I have one list of objects
var listOfUsr = new List<User>();
listOfUsr = GetUserByAgentId("some_id");
if (listOfUsr != null)
{
DropDownList.DataSource = listOfModels;
//DropDownList.DataTextField = "how to set value_from User.Name ?";
//DropDownList.DataValueField = "how to set value_from User.ID ?";
DropDownList.DataBind();
}
How can I set text and value field from object properties?
You just have to set Column Name in DataTextField and DataValueField.
In your case Name and ID are column names for your list object of user.
if (listOfUsr != null)
{
DropDownList.DataSource = listOfModels;
DropDownList.DataTextField = "Name";
DropDownList.DataValueField = "ID";
DropDownList.DataBind();
}
You could try this one:
DropDownList.DataTextField = "Name";
DropDownList.DataValueField = "ID";
I suppose, as it can be concluded from your comments, that an object of type User has two properties called Name and ID and these are the text and value correspondingly that you want to show.
Use a ComboBox and set DropDownStyle =ComboBoxStyle.DropDownList;
Try this code:
var listOfUsr = new List<User>();
listOfUsr = GetUserByAgentId("some_id");
comboBox1.DropDownStyle =ComboBoxStyle.DropDownList;
comboBox1.DataSource=lstOfUsr;
comboBox1.DisplayMember="Description";
You can also drag an object of type BindingSource and use it in this mode:
var listOfUsr = new List<User>();
listOfUsr = GetUserByAgentId("some_id");
bindingSourceListOfObject.DataSource = lstOfUsr;
comboBox1.DropDownStyle =ComboBoxStyle.DropDownList;
comboBox1.DataSource=bindingSourceListOfObject;
comboBox1.DisplayMember="Description";
With BindingSource have many possibilities and flexibility on complex scenario.
Related
I am two Combobox which are populated with a view of a table like following
recieverComboBox.DataSource = myDataSet.Tables[0].DefaultView;
recieverComboBox.DisplayMember = "UserPosition";
recieverComboBox.ValueMember = "ID";
recieverUnReadComboBox.DataSource = myDataSet.Tables[0].DefaultView;
recieverUnReadComboBox.DisplayMember = "UserPosition";
recieverUnReadComboBox.ValueMember = "usr_Id";
when I change the value of each of them, the value of the other one changes automatically. why is that ?
Here are two ways to avoid this issue.
Solution A:
Use BindingSource as the DataSource of ComboBox.
recieverComboBox.DataSource = new BindingSource(myDataSet.Tables[0].DefaultView, null);
recieverComboBox.DisplayMember = "UserPosition";
recieverComboBox.ValueMember = "ID";
recieverUnReadComboBox.DataSource = new BindingSource(myDataSet.Tables[0].DefaultView, null);
recieverUnReadComboBox.DisplayMember = "UserPosition";
recieverUnReadComboBox.ValueMember = "usr_Id";
Solution B:
Call method DataTable.Copy
recieverComboBox.DataSource = myDataSet.Tables[0].Copy();
recieverComboBox.DisplayMember = "UserPosition";
recieverComboBox.ValueMember = "ID";
recieverUnReadComboBox.DataSource = myDataSet.Tables[0].Copy();
recieverUnReadComboBox.DisplayMember = "UserPosition";
recieverUnReadComboBox.ValueMember = "usr_Id";
I want to set my data from my database into the CheckedListBox but with my code I only get error messages that say DataBinding only accepts List or ListSource.
Also with debugging mode I don't even get an error message the CheckedListBox just stays empty.
DataClasses1DataContext d = new DataClasses1DataContext();
////
var query = from pers in d.Person select pers;
BindingList<Person> personen = new BindingList<Person> { new Person { Name = "Name"} };
clVorfahr.DataSource = personen;
clVorfahr.DisplayMember = "Name";
clVorfahr.ValueMember = "Name";
clVorfahr.Refresh();
You are setting the wrong data source. It should be personen not Name.
clVorfahr.DataSource = personen;
clVorfahr.DisplayMember = "Name";
To follow my previous post here => Binding SelectedItem of ComboBox in DataGrid with different type
I have now a datagrid containing 2 columns, one with a text, the other with a combobox (in a datatemplate, written thru the C# code, not the Xaml).
After having done some choice on the combobox, I now would like to parse the result but the value of the cell containing my combobox stay empty :
foreach(DataRowView row in Datagrid1.Items)
{
var firstColumNresult = row.Row.ItemArray[0];// Return correctly a string
var myrow = row.Row.ItemArray[1];// always empty...
}
The result is that I cant get the values of my (previously generated) combobox.
I suppose one binding must missed somewhere...
This is the combobox creation code :
DataTable tableForDG = new DataTable();
tableForDG.Columns.Add(new DataColumn { ColumnName = "Name", Caption = "Name" });
tableForDG.Columns.Add(new DataColumn { ColumnName = "Attachment", Caption = "Attachment" }); // this column will be replaced
tableForDG.Columns.Add(new DataColumn { ColumnName = "AttachmentValue", Caption = "AttachmentValue" });
tableForDG.Columns.Add(new DataColumn { ColumnName = "DisplayCombo", Caption = "DisplayCombo", DataType=bool });
// Populate dataview
DataView myDataview = new DataView(tableForDG);
foreach (var value in listResults)// a list of string
{
DataRowView drv = myDataview.AddNew();
drv["Name"] = value.Name;
drv["Attachment"] = value.Name;// this column will be replaced...
drv["DisplayCombo"] = true;// but it can be false on my code...
}
var DG = myDataview;//
Datagrid1.ItemsSource = DG;
Datagrid1.AutoGenerateColumns = true;
Datagrid1.Items.Refresh();
DataGridTemplateColumn dgTemplateColumn = new DataGridTemplateColumn();
dgTemplateColumn.Header = "Attachment";
var newCombobox = new FrameworkElementFactory(typeof(ComboBox));
newCombobox.SetValue(ComboBox.NameProperty, "myCBB");
Binding enableBinding = new Binding();
newCombobox.SetValue(ComboBox.IsEnabledProperty, new Binding("DisplayCombo"));
newCombobox.SetValue(ComboBox.SelectedValueProperty, new Binding("AttachmentValue"));
List<string> listUnitAlreadyAttached = new List<string>();
// fill the list...
enableBinding.Source = listUnitAlreadyAttached;
newCombobox.SetBinding(ComboBox.ItemsSourceProperty, enableBinding);
var dataTplT = new DataTemplate();
dataTplT.VisualTree = newCombobox;
dgTemplateColumn.CellTemplate = dataTplT;
Datagrid1.Columns[1] = dgTemplateColumn;
Any idea/advice ?
You should explicitely specify the binding mode and update trigger of your binding. Also use SetBinding instead of SetValue:
var valueBinding = new Binding("AttachmentValue")
{
Mode = BindingMode.TwoWay,
UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged
};
newCombobox.SetBinding(ComboBox.SelectedValueProperty, valueBinding);
This should enable you to get the selected value into your row data. It might not update in the displayed datagrid value for the AttachmentValue column.
I have a combobox with objects of Foo type, here is the Foo class:
public class Foo
{
public string name { get; set; }
public string path { get; set; }
}
The Foo.name is the displayed text in the combobox and Foo.path is the value of the selected option.
I want to delete an option from the combobox after some operation I made.
I've tried these ways:
1
comboBox2.Items.Remove(#comboBox2.Text);
2
comboBox2.Items.Remove(#comboBox2.SelectedValue.ToString());
3
Foo ToDelete = new Foo();
ToDelete.name = #comboBox2.Text;
ToDelete.path = #comboBox2.SelectedValue.ToString();
comboBox2.Items.Remove(ToDelete);
Nothing works for me. : / How to do this?
UPDATE
This is how I'm initializing my combobox:
string[] filePaths = Directory.GetFiles(sites.paths[comboBox1.SelectedIndex]);
List<Foo> combo2data = new List<Foo>();
foreach (string s in filePaths)
{
Foo fileInsert = new Foo();
fileInsert.path = s;
fileInsert.name = Path.GetFileName(s);
combo2data.Add(fileInsert);
}
comboBox2.DataSource = combo2data;
comboBox2.ValueMember = "path";
comboBox2.DisplayMember = "name";
comboBox2.Items.Remove(comboBox2.SelectedValue); will only remove from the combobox, not from the datasource bound to the combobox. You may remove it from the datasource and re-bind the datasource.
Use ComboBox.SelectedIndex property.
For example: let me have comboBox1 added to the form. In the delete button:
if (comboBox1.SelectedIndex >= 0)
comboBox1.Items.RemoveAt(comboBox1.SelectedIndex);
combox1.Remove(takes an object)
Object selectedItem = comboBox1.SelectedItem;
So you cna do it this way combox1.Remove(selectedItem);
Suppose you want to Remove Items by Index:
combo2data.RemoveAt(0); //Removing by Index from the dataSource which is a List
//Rebind
comboBox2.DataSource = null;
comboBox2.DataSource = combo2data;
comboBox2.ValueMember = "path";
comboBox2.DisplayMember = "name";
Suppose you want to Remove by seraching for a member value
Foo item = combo2data.Where(f => f.name.Equals("Tom")).FirstOrDefault();
if (item != null)
{
combo2data.Remove(item);
comboBox2.DataSource = null;
comboBox2.DataSource = combo2data;
comboBox2.ValueMember = "path";
comboBox2.DisplayMember = "name";
}
These 2 commands will remove an item from your data source.
list.Remove((Foo)comboBox1.SelectedItem);
or
list.Remove(list.Find(P=>P.name == comboBox1.SelectedText));
I think the secret is to first attribute null to the datasource and after rebind to a modified collection:
int idToRemove = 1;
var items = (cbx.DataSource as List<MyEntity>);
items.RemoveAll(v => v.Id == idToRemove);
rebindCombobox(cbx, items, "Name", "Id");
private void rebindCombobox(ComboBox cbx, IEnumerable<Object> items, String displayMember, String valueMember)
{
cbx.DataSource = null;
cbx.DisplayMember = displayMember;
cbx.ValueMember = valueMember;
cbx.DataSource = items;
}
Perhaps delete all items in the Combobox with
comboBox.Items.Clear();
//Instead of the this
var tableX = db.PRODUCT; //db is the DataContext
//I can do the below (Thanks to http://stackoverflow.com/questions/1919632/get-table-data-from-table-name-in-linq-datacontext
string tablename = "PRODUCT";
var table = (ITable)db.GetType().GetProperty(tablename).GetValue(db, null);
//But instead of this
PRODUCT _Product = new PRODUCT();
_Product.PRD_CODE = "code1";
_Product.PRD_DESC = "description1";
table.InsertOnSubmit(_Product);
db.SubmitChanges();
//How can I do something like this
string tablename = "PRODUCT";
var table = (ITable)db.GetType().GetProperty(tablename).GetValue(db, null);
string lsColumnPrdCode = "PRD_CODE";
string lsColumnPrdDesc = "PRD_DESC";
table _tableInstance = new table();
_tableInstance[lsColumnPrdCode] = "code1";
_tableInstance[lsColumnPrdDesc] = "description1";
_tableInstance.InsertOnSubmit(_tableInstance);
db.SubmitChanges();
So it is possible to set datacontext column values without strongly typing it?
Of cause you can use reflection to do that kind of stuff. Maybe something similar to this code:
Type productType = Type.GetType("PRODUCT");
var product = Activator.CreateInstance(productType);
productType.GetProperty("PRD_CODE").SetValue(product, "code1");
productType.GetProperty("PRD_DESC").SetValue(product, "description1");
Type tableType = table.GetType();
tableType.GetMethod("InsertOnSubmit").Invoke(table, new object[] {product});
But why do you want to do that?