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";
Related
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 want to fill my ListBox 'lstCategories' with the content of a database and all I see is nothing, here's the code :
public void FillCategories()
{
SamsonEntities db = new SamsonEntities();
var ListCats = (from cat in db.Categories
select new CategoryDisplay()
{
CategoryID = cat.CategoryID,
CategoyName = cat.CategoryName
}).ToList();
//for (var i = 0; i < db.Categories.Count();i++ )
//{
// lstCategories.Items.Add(....);
//}
}
I don't know what to place into the line of my 'for', so I put it in comments
Have you tried setting the list as the ListBox datasource?
lstCategories.DataSource = ListCats;
That should be enough.
As per your comment you need to set up the DisplayMember of your list to match the property to show:
lstCategories.DisplayMember = "CategoryName";
And you probably want to setup the ValueMember too:
lstCategories.ValueMember = "CategoryID";
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.
I have a database attached to a C# project, with 3 tables Company, Product, and Inventory. Inventory lists CompanyID, ProductID, and Quantity. Combobox1 lists all the companyID. When you select one, I want listview1 to display only the rows in Inventory with that CompanyID.
//binding DB to memorycopy
this.DBContext = new DBEntities();
listView1.ItemsSource = this.SupPartContext.SPs;
GridViewColumn companyIDColumn = new GridViewColumn();
sNumColumn.Width = 90;
sNumColumn.Header = "companyID";
sNumColumn.DisplayMemberBinding = new Binding("COMPANYID");
GridViewColumn ProductIDColumn = new GridViewColumn();
pNumColumn.Width = 90;
pNumColumn.Header = "ProductID";
pNumColumn.DisplayMemberBinding = new Binding("PRODUCTID");
GridViewColumn quantityColumn = new GridViewColumn();
qtyColumn.Width = 90;
qtyColumn.Header = "quantity";
qtyColumn.DisplayMemberBinding = new Binding("QUANTITY");
GridView newGridview = new GridView();
newGridview.Columns.Add(companyIDColumn);
newGridview.Columns.Add(productIDColumn);
newGridview.Columns.Add(quantityColumn);
listView1.View = newGridview;
Any help, even a point in the right direction would be appreciated. Thank you for your time.
If you are wanting the list view to change automatically without writing any code you're probably not going to be able to get that to happen. However, if you rebind the list when the combo box value changes with the following line it will filter the list as you expect.
listView1.ItemsSource = this.SupPartContext.SPs.Where(sp => sp.CompanyID = {get the select company from the row here})
Design class which is generated by C# :
//
// usepurposeComboBox
//
this.usepurposeComboBox.DataSource = this.usepurposeBindingSource;
this.usepurposeComboBox.DisplayMember = "Name";
this.usepurposeComboBox.FormattingEnabled = true;
this.usepurposeComboBox.Location = new System.Drawing.Point(277, 53);
this.usepurposeComboBox.Name = "usepurposeComboBox";
this.usepurposeComboBox.Size = new System.Drawing.Size(218, 21);
this.usepurposeComboBox.TabIndex = 4;
this.usepurposeComboBox.ValueMember = "id";
//
// usepurposeBindingSource
//
this.usepurposeBindingSource.DataSource = typeof(mydatabaseEntities.usepurpose);
Then I bound the BindingSource (usepurposeBindingSource) to Entities :
usepurposeBindingSource.DataSource = mydatabaseEntities.usepurposes;
And I can not add a new row to usepurposeComboBox because it's been bound. Is there a workaround ?
The shortest way is to add a new row to your dataTable and then bind your comboBox to it something like this:
Company comps = new Company();
//pupulate dataTable with data
DataTable DT = comps.getCompaniesList();
//create a new row
DataRow DR = DT.NewRow();
DR["c_ID"] = 0;
DR["name"] = "Add new Company";
DR["country"] = "IR";
//add new row to data table
DT.Rows.Add(DR);
//Binding DataTable to cxbxCompany
cxbxCompany.DataSource = DT;
cxbxCompany.DisplayMember = "name";
cxbxCompany.ValueMember = "c_ID";
I'm assuming that you want to add for example a first item sometimes called "Choose One" as if you want to live data you should just see where the data comes from and add more items to that "table".
this.usepurposeBindingSource is an object ... why not adding into it before it binds?
if it's a List<T> this will be fine
this.usepurposeBindingSource.Insert(0, new T() {
Name = "Choose one",
Id = ""
});
Then Bind() it...
Remember to validate as it's a string and will not be the object you want
This is working:
List<MyObject> usepurposeBindingSource { get; set; }
private void FillUpData()
{
// Simulating an External Data
if (usepurposeBindingSource == null || usepurposeBindingSource.Count == 0)
{
this.usepurposeBindingSource = new List<MyObject>();
this.usepurposeBindingSource.Add(new MyObject() { Name = "A", ID = 1 });
this.usepurposeBindingSource.Add(new MyObject() { Name = "B", ID = 2 });
this.usepurposeBindingSource.Add(new MyObject() { Name = "C", ID = 3 });
}
}
private void FillUpCombo()
{
FillUpData();
// what you have from design
// comment out the first line
//this.usepurposeComboBox.DataSource = this.usepurposeBindingSource;
this.usepurposeComboBox.DisplayMember = "Name";
this.usepurposeComboBox.FormattingEnabled = true;
this.usepurposeComboBox.Location = new System.Drawing.Point(277, 53);
this.usepurposeComboBox.Name = "usepurposeComboBox";
this.usepurposeComboBox.Size = new System.Drawing.Size(218, 21);
this.usepurposeComboBox.TabIndex = 4;
this.usepurposeComboBox.ValueMember = "id";
// to do in code:
this.usepurposeBindingSource.Insert(0, new MyObject() { Name = "Choose One", ID = 0 });
// bind the data source
this.usepurposeComboBox.DataSource = this.usepurposeBindingSource;
}
The trick is to comment out the DataSource line and do it in your code, inserting one more element into your object that is from your Model
//this.usepurposeComboBox.DataSource = this.usepurposeBindingSource;
The simplest way to do this, is to wrap your BindingSource with some kind of "ViewModel". The new class will return a "complete" list of items - both those provided from the original binding source, as well as those "additional" items.
You can then bind the new wrapper to your combobox.
I wrote an article about this a while back... It's not my finest work, and it's probably a bit outdated, but it should get you there.
I resolved it on my own. I created a new unbound combobox then bind it to a datatable. Not sure if it's the best way but it works for me. Thanks for all of your suggestions. :)
private void FillCombobox()
{
using (mydatabaseEntities mydatabaseEntities = new mydatabaseEntities())
{
List<usepurpose> usepurposes = mydatabaseEntities.usepurposes.ToList();
DataTable dt = new DataTable();
dt.Columns.Add("id");
dt.Columns.Add("Name");
dt.Rows.Add(-1, "test row");
foreach (usepurpose usepurpose in usepurposes)
{
dt.Rows.Add(usepurpose.id, usepurpose.Name);
}
usepurposeComboBox.ValueMember = dt.Columns[0].ColumnName;
usepurposeComboBox.DisplayMember = dt.Columns[1].ColumnName;
usepurposeComboBox.DataSource = dt;
}
}
Check out this link: http://forums.asp.net/t/1695728.aspx/1?
In asp you can add this to insert an empty line:
<asp:DropDownList ID="CustomerDropDownList" runat="server"
DataSourceID="CustomerEntityDataSource" DataTextField="CustomerId"
DataValueField="CustomerId" AppendDataBoundItems="true">
<asp:ListItem Text="Select All Customers" Value="" />
</asp:DropDownList>
Or in code behind:
DropDownList1.AppendDataBoundItems = true;
DropDownList1.Items.Add(new ListItem("Select All Customers", "-1"));