Error with data grid view - c#

I'm having problem with datagrid view. I have attached an image with the code & error message. I want to know the reason of this error. Thanks.

You don't need the LINQ query. just set the list as the DataSource. There is no need to set the DataMember in this case.
private void Form4_Load(object sender, EventArgs e)
{
List<Products> productList = new List<Products>()
{
new Products{ProductName = "P1", ProductPrice = 56, Category = "c1"},
new Products{ProductName = "P2", ProductPrice = 36, Category = "c1"}
};
//var p = from s in productList select s;
dataGridView1.DataSource = productList;
//dataGridView1.DataMember = p.ToString();
}
EDIT
LINQ query is returning IEnumerable; however the DataGridView class supports the standard Windows Forms data-binding model. This means the data source can be of any type that implements one of the following interfaces: IList, IListSource, IBindingList, and IBindingListView. So you will need to call ToList() to your LINQ result. Read more about this on this MSDN Link
However in your case doing this is same as setting productList as DataSource (I mean the results will be the same, as there is no sorting or grouping involved in the LINQ query).
If you want to play with LINQ, try this out (your list will be ordered by ProductPrice in ascending order)
var p = from s in productList orderby s.ProductPrice select s;
dataGridView1.DataSource = p.ToList();

Instead of setting the DataMember simply call the bind method dataGridView1.DataBind(). As stated by MSDN the DataMember is used for the following:
Gets or sets the name of the list or table in the data source for which the DataGridView is displaying data.

Related

Binding DropdownList with a nested json result

I have for the most part successfully connected to an API endpoint and manage to deserialize nested json result and bind it to a gridview using Newtonsoft.Json serialization attributes.
I however cannot bind to a dropdownlist. What is the correct property name to use to pass the supplier name to my dropdownlist?
I can see the property I want to pass (supplier name) and have tried all possible strings I can think of but all I get is the class name to display.
The Supplier Name displays fine on the gridview
I can see the property I want to display supplier -> name
Binding Code
var readdata = comsumeapi.Result;
if (readdata.IsSuccessStatusCode)
{
var displayrecords = readdata.Content.ReadAsAsync<IList<CoupaPODetails>>();
displayrecords.Wait();
empobj = displayrecords.Result;
GridView1.DataSource = empobj;
GridView1.DataBind();
DropDownList1.DataSource = empobj;
DropDownList1.DataTextField = "supplier";
DropDownList1.DataBind();
}
It would have been quite helpful to see your JSON object code but I think I can glean what I need from the screenshots
You've bound the drop down list to supplier object, not the name of the supplier. I think you should probably make a new list of all the different suppliers and bind to that, something like:
var x = empobj.Select(e => e.supplier.name).Distinct().ToList();
(Your supplier object only seems to contain a name? This a bit odd why there would even be a supplier object at all if it only houses a string. I figured it might contain more than that , like a name and an ID. If it contains more than that and you want a display text and a value that are different, use one of the techniques from here to group by eg the value and then linq .Select(g => new ListItem(){Text = g.First(), Value = g.Key}) to generate a List<ListItem> that can be the datasource for your drop down)
Don't forget that you'll also need to bind to the grid's row data bound event to set the selected item in the drop down, detail for which is here

Manually Populating and Selecting ComboBox Items

I can't believe how difficult this simple task is.
I have the following code:
cboCountry.ValueMember = "ID";
cboCountry.DisplayMember = "Title";
var countries = from c in context.Set<sc_Countries>()
orderby c.Title
select new { c.ID, c.Title };
Now, I want to populate the ComboBox cboCountry with this collection, and then I want to select the list item with the ID (value) "US".
I was able to add the items to the ComboBox using cboCountry.Items.AddRange(countries.ToList()), but then cboCountry.SelectedValue = "US" had no effect.
Next, I tried adding the collection using cboCountry.DataSource = countries but this just left the control list empty.
Surely there must be a simple way to accomplish this trivial task. Can anyone offer the missing ingredient?
Until you call ToList() on your LINQ statement, you're not actually getting data from the database:
var countries = (from c in context.Set<sc_Countries>()
orderby c.Title
select new { c.ID, c.Title }).ToList();
Now you should be able to set the DataSource, etc. like you were:
cboCountry.ValueMember = "ID";
cboCountry.DisplayMember = "Title";
cboCountry.DataSource = countries;
cboCountry.SelectedValue = "US"
Edit:
Now that I'm re-reading your question, it looks like you were already calling countries.ToList(), but using Items.AddRange. I see the same thing you do when I try it. It appears you have to set the DataSource instead of using Items.AddRange, for SelectedValue to work.

Silverlight C#: How to filter a combobox based on another combobox?

How to filter a combobox based on another combobox? ... again :)
I'm writing an web app to learn. I'm using Visual Studio 2012, Silverlight 5, C#, and SQl Server for the data source.
I have one table loading into a datagrid and comboboxes to filter the datagrid. Up to this point everything is working just right.
The comboboxes are "FilterState" and "FilterWaterWay". Note they are not in the datagrid.
I want to select a state and re-populate the FilterWaterWay with only those waterways in the state.
I've seen a lot of ways to do this but none of them seem to match my setup. I could be wrong and just not know it.
From a learning standpoint, I would like to know how to implement this in all 3 of the following query data examples but I'll settle for just one. The last one is my favorite.
Thanks for any and all help.
I would not mind using the following to load comboboxes, filtered or not, but I can't firgure out how to
Restirct the GetQuery to only one field
Make that field distinct
This loads all data from the GetQuery to the datagrid.
LoadOperation<MASTER_DOCKS> loadOp = this._DocksContext.Load(this._DocksContext.GetMASTER_DOCKSQuery());
DocksGrid.ItemsSource = loadOp.Entities;
This loads all data from the GetQuery to the datagrid after it's been filtered
EntityQuery<MASTER_DOCKS> query = _DocksContext.GetMASTER_DOCKSQuery();
query = query.Where(s => s.WTWY_NAME == WaterwaytoFilterBy && s.STATE == StateToFilterBy);
LoadOperation<MASTER_DOCKS> loadOp = this._DocksContext.Load(query);
DocksGrid.ItemsSource = loadOp.Entities;
This is how I am currently loading the comboboxes. This works fine for the load but I don't see how to filter.
The DomainService.cs does not know my other combobox (FilterState) that I want to use as the filter for this combobox (FilterWaterway).
If I could query the ObservableCollection in the xaml I might be able to get it to work but it seems kind of chunky.
Adapted from http://www.jonathanwax.com/2010/10/wcf-ria-services-datagrid-filters-no-domaindatasource-2/
XAML =
private ObservableCollection<string> waterWayFilterList;
public ObservableCollection<string> WaterWayFilterList
{
get { return waterWayFilterList; }
set { waterWayFilterList = value; }
}
private void DoPopulateFilter()
{
//Call Invoke Method to get a list of distinct WaterWays
InvokeOperation<IEnumerable<string>> invokeOp = _DocksContext.FillWaterWayList();
invokeOp.Completed += (s, e) =>
{
if (invokeOp.HasError)
{
MessageBox.Show("Failed to Load Category Filter");
}
else
{
//Populate Filter DataSource
WaterWayFilterList = new ObservableCollection<string>(invokeOp.Value);
//Add a Default "[Select]" value
WaterWayFilterList.Insert(0, "[Select WaterWay]");
FilterWaterWay.ItemsSource = WaterWayFilterList;
FilterWaterWay.SelectedItem = "[Select WaterWay]";
}
};
}
DomainService.cs =
[Invoke]
public List<string> FillWaterWayList()
{
return (from r in ObjectContext.MASTER_DOCKS
select r.WTWY_NAME).Distinct().ToList();
}
Here's the closest I've gotten so far and it seems straight forward.
It returns no errors but the displayed result reads System.Collections.Generic.List'1[System.Char]
The record count in the dropdown is correct which leads me to think it's on the right track.
Only what is displayed is wrong. A casting problem perhaps?
I would still have to get the result from the FilterState Combo box in where "TX" is.
var filter = from r in _DocksContext.MASTER_DOCKS
where r.STATE.Equals("TX")
select r.WTWY_NAME.Distinct().ToList();
MyComboBox.ItemsSource = filter;
Without parentheses, you're doing the .Distinct().ToList() on the string (which implements IEnumerable<char>, which is why those operations work), which results in a List<char> (which isn't what you're looking for). You need to add parentheses so you get the distinct waterways:
var filter = (from r in _DocksContext.MASTER_DOCKS
where r.STATE.Equals("TX")
select r.WTWY_NAME).Distinct().ToList();
Note that if two waterways might have the same name, but actually be distinct, you'll need to instead select distinct r, and then differentiate them in the dropdown somehow, e.g.
var filter = (from r in _DocksContext.MASTER_DOCKS
where r.STATE.Equals("TX")
select r).Distinct().ToList();
// generated classes are partial, so you can extend them in a separate file
public partial class MASTER_DOCKS
{
// the dropdown uses the ToString method to show the object
public override string ToString()
{
return string.Format("{0} ({1})", WTWY_NAME, ID);
}
}

Binding BindingList<string[]> to datagridview

Situation:
I am attempting to bind a BindingList<string[]> constructed from a LINQ to SQL query to a DataGridView.
Problem:
I either cannot make modification to the DataGridView after items are generated -or- I get a bunch of unwanted fields in my DataGridView (it depends on which iteration of my code I use) I have googled as hard as I can and tried implementing most of the solutions I have found online to no avail.
I know that string has no public property for its actual value. I am having a difficult time determining how to retrieve that (I believe is part of the problem).
C#
int item = (from p in CurrentConversion.Companies[lbCompanies.SelectedIndex].Modules
where p.ModuleName.Equals(clbModules.SelectedItem)
select p.ModuleId)
.FirstOrDefault();
BindingList<string[]> Data = new BindingList<string[]>((
from p in CurrentConversion.Companies[lbCompanies.SelectedIndex].QuestionAnswers
where p[2].Equals(item)
select new string[] { p[0].ToString(), p[3].ToString() })
.ToList());
dgvQuestions.DataSource = Data;
dgvQuestions.Refresh();
Unwanted Behavior:
This occurs after binding
Question:
Why is this happening?
How do I fix it?
Additional Information:
I am not sure what additional information may be need but I will supply what is requested.
Also if I switch to my other code iteration:
int item = (from p in CurrentConversion.Companies[lbCompanies.SelectedIndex].Modules where p.ModuleName.Equals(clbModules.SelectedItem) select p.ModuleId).FirstOrDefault();
var Data = new BindingList<object>((from p in CurrentConversion.Companies[lbCompanies.SelectedIndex].QuestionAnswers where p[2].Equals(item) select new {Question = p[0].ToString(), Answer = p[3].ToString() }).Cast<object>().ToList());
dgvQuestions.DataSource = Data;
dgvQuestions.Refresh();
dgvQuestions.Columns[1].ReadOnly = false;
I can see the data properly but I cannot edit the column I would like to.
You are binding to a list of string arrays, and you are getting the properties form the array. Most likely you want something like the following:
var Data = new BindingList<object>((
from p in CurrentConversion.Companies[lbCompanies.SelectedIndex].QuestionAnswers
where p[2].Equals(item)
select new {
Val1 = p[0].ToString(),
Val2 = p[3].ToString()
}).ToList());
The reason you're seeing those fields in the Grid is that you're binding each row to a string[]. So it is automatically displaying the properties of string[] as the columns. There is no built-in logic for the grid to parse an array and use the contents of the array as columns.
In order to get the DataGrid to display your data correctly, you should bind it to a custom type, and it will use the public properties of the type as columns.

Sort datagridview by created columns. Entity Framework c# Winforms

I´m having a problem, I retrieve all the Loans I have stored in my database like this:
list_loans = db.Loan.Where(x => x.State.id_state != 6).ToList();
db is the Object context.
Then, I assign that list as the DataSource for my DataGridView.
dgv_Loans.Datasource = list_loans;
With that info, I add some columns. Like for example, installments left to pay. I get that value by counting the result of a query.
The user can order the result using some options. Is easy to order the result from the fields that the entity have (using linq), but I dont know how to order the results using this new columns.
I read some posts here and tried this:
dgv_Loans.Sort(dgv_Loans.Columns["installments_left"], ListSortDirection.Ascending);
By doing this, I´m getting the following exception at runtime:
"DataGridView control must be bound to an IBindingList object to be sorted."
Is there anyway to use linq to orderby created columns in a DataGridViewColumn? Or how can I solve this error?
I know there are related posts, but after reading them, I can´t find a solution to this specific problem. Thats why I showed how I implemented to get some advice..
Rather than binding directly to the list retrieved from database, what I generally do is have a view class and have all the calculated properties in that class
public class LoanView : Loan {
public LoanView(Loan loan){
}
public int InsallmentsLeft { get { return ...; } }
}
and then bind the datasource to a list of this, this keeps sorting working.
Concerning about Sort datagridview by created columns using Entity Framework
I guess you need this Presenting the SortableBindingList<T>
Usage:
loanBindingSource.DataSource = new SortableBindingList<Loan>(list_loans.ToList());
dgv_Loans.Datasource = loanBindingSource;
int ID = Convert.ToInt32(cmbDepartments.SelectedValue);
var EmployeeList = from Employee in db.Employee
where Employee.DepartmentID == ID
select new
{
Employee.FirstName,
Employee.LastName
};
dataGridView1.DataSource = EmployeeList.ToList();
You could directly give the data source to dataGridView1.DataSource but you must write ToList() at the end of your query:
int ID = Convert.ToInt32(cmbDepartmanlar.SelectedValue);
dataGridView1.DataSource = (from Employee in db.Employee
where Employee.DepartmentID == ID
select new
{
Employee.FirstName,
Employee.LastName
}).ToList();

Categories