Updating of BindingSource in WinForms - winforms

During my attempts to use DataBinding in Winforms I've encountered with a problem. It looks like after updating of DataSource DataGridView doesn't refresh the data. Can't understand where is a problem.
var companies = new List<Company> { new Company { Name = "Test", Id = 100 }}
And here is the code for binding of items list to DataGridView:
bindingSource1.DataSource = _context.Companies;
dataGridView1.DataSource = bindingSource1.DataSource;
But after that if I update companies list like this
companies.Add(new Company { Name = "MDG", Id = 500 });
I can't find the newly added item into the DataGridView. Could someone help me to understand what I'm missing?

The problem here is that there is no way the BindingSource and the DataGridView can be made aware of changes to a List automatically.
Instead, use a new BindingList(). This has events that will be called to notify the BindingSource, and in turn the DataGridView that a new item to the list has been added.
var companies = new BindingList<Company>();
companies.Add(new Company { Name = "Test", Id = 100 });

Related

MVVM database delete Method

I want to DELETE some items from my Model which I generated from the database like that:
db = new TestDBEntities();
foreach (var item in db.Farbe)
{
_model.Add(new Farbe { FarbauswahlNr = item.FarbauswahlNr, Kurztext = item.Kurztext, Ressource = item.Ressource,Vari1 = Convert.ToBoolean(item.Var1) ,Vari2 = item.Vari2 });
}
I'm showing this Model in a RadGridView and deleting by Selecting and Index per Rightcklick on the mouse like this:
public void ExecuteDelete(object obj)
{
farbliste.Model.Remove(SelectedIndex);
ListeAktualisieren();
}
Now the question is how do I Delete something from my Database because if I just Delete from my Model it wont work and that's also not what I want.
Btw some variable are named in German sorry...
you have to save your context. Your context in the first block of code is db.
So:
db = new TestDBEntities();
db.entity.Remove(db.entity.Find(SelectedIndex));
db.SaveChanges();
Entity is the name of your table/object from entity frramework. I would also suggest wraping this is a using block for the db

How can Add items to Binded Datasource Combo Box?

Hi I am new to C#. I have tried following way to add new item to my bound ComboBox but it won't give any result.
Is it possible to add new item to bound ComboBox (Here Problem is ID is Bigint data type but I want to add Select ID)?
If it is possible, please provide piece of code
try
{
objSqlExecute.OpenConnection();
string strQuery = objQueryManager.GetEmployeeRecords();
//Add Extra Items to combo Box
cmbEmployeeID.Items.Add("Select Id");
DataTable dtEmployee = objSqlExecute.GetRecordExecution(strQuery);
// DataRow dtNew = dtEmployee.NewRow();
// dtNew["ID"] = "Select ID";
// dtNew["FName"] = "";
//dtEmployee.Rows.InsertAt(dtNew, 0);
cmbEmployeeID.DataSource = dtEmployee;
cmbEmployeeID.DisplayMember = "ID";
cmbEmployeeID.ValueMember = "FName";
}
try
{
objSqlExecute.OpenConnection();
string strQuery = objQueryManager.GetEmployeeRecords();
//Add Extra Items to combo Box
DataTable dtEmployee = objSqlExecute.GetRecordExecution(strQuery);
cmbEmployeeID.DataSource = dtEmployee;
cmbEmployeeID.DisplayMember = "ID";
cmbEmployeeID.ValueMember = "FName";
cmbEmployeeID.Items.Insert(0, "None Selected");
}
Did you try your query to make sure it returns values? returning multiple records, single or none?
Do you want to add ONE new item at random intervals?
Or else do you have an option to INSERT all items at once?
Can you try adding toString() for converting BigInt?
Notes:
The arcticle here gives an insight to add a new item to a combobox using sql.
Looking at the questions you are posting, to see a sample of how to use ListItems in this scenario, you could refer to the web link.

Silverlight 5 datagrid is missing data

I am trying to bind an xml data set to a Silverlight data grid. There are 21 rows in my xml The grid shows the heading ok and the 21 rows but the rows show no data. If I look at the ItemsSource property it shows the row date as being there.
I am having a problem posting all the code because of the edits that Stack Overflow does. Here is the key piece. If you need to see anything else, I will post it as comments.
grdData.ItemsSource = cloData.LoadData("Sample.xml")
public class clsData
{
public System.Collections.IEnumerable LoadData(string pName)
{
XDocument nutritionsDoc = XDocument.Load(pName);
List<Nutrition> data = (from nutrition in nutritionsDoc.Descendants("Nutrition")
select new Nutrition
{
Group = nutrition.Attribute("Group").Value,
Name = nutrition.Attribute("Name").Value,
Quantity = nutrition.Attribute("Quantity").Value
}).ToList();
return data;
}
}
What am I missing?
I just made the nutrition class a public class and it was magically solved.
Bob

Can't add new item to Silverlight DataForm when ICollectionView is sorted or filtered

I've got a DataForm on a Silverlight 4 page. I bind it to the View on the class below. I am able to add, delete, edit, and move forward/back through records just fine using the controls built into the DataForm. But as soon as I remove the comment for the Filter or SortDescription, then every time I press the Add + button I get the dreaded "cannot change currency when an item has validation errors or it is being edited and AutoCommit is false" error. I've been stuck on this for hours and don't have a clue.
public class TestData {
OperationsDataContext context;
ICollectionView view;
public ICollectionView View { get { return view; } }
public IEditableCollectionView EditableView { get { return ((IEditableCollectionView)view); } }
public TestData() {
context = new OperationsDataContext();
context.Locations.Add(new Location { LocationId = 1, LocationName = "Home", CreatorUserId = 1 });
context.Locations.Add(new Location { LocationId = 2, LocationName = "Work", CreatorUserId = 1 });
context.Locations.Add(new Location { LocationId = 3, LocationName = "Office", CreatorUserId = 1 });
view = ((ICollectionViewFactory)context.Locations).CreateView();
// View.Filter = (o) => true;
// View.SortDescriptions.Add(new SortDescription("LocationName", ListSortDirection.Ascending));
}
}
I have attempted to add data manually using code - not the DataForm - and it works just fine even when both a filter and sort are specified.
TestData testData = new TestData();
Location item = testData.EditableView.AddNew() as Location;
testData.EditableView.CommitNew();
Why would it work from code but not via the DataForm? And why does the DataForm work when no filter is specified, but fail when a no-op filter that always returns true is specified?
may be you have similar issue as http://forums.silverlight.net/p/111217/250982.aspx post
Okay, so I just ran into the exact same issue. In my case, I was using a DomainCollectionView that was bound to both, a DataGrid and a DataForm. Apparently, this can cause issues because both controls want to manage the currency.
The solution was to not bind the DataForm directly to the DomainCollectionView, but instead to bind it to the DomainCollectionView.SourceCollection property.
The downside to this is that you have to bind DataGrid.SelectedItem and DataForm.CurrentItem to keep them both in sync. I have not found any other issues with this approach, but it definitely solved the error when trying to add a new item after sorting in the DataGrid.
See the comment from Jeff Handley about this issue: http://jeffhandley.com/archive/2011/08/02/ToolkitAugust2011.aspx

I can't get my SharePoint ListItem Fields

I want to show all fields of a certain ListItem. This includes LookUpFields and ChoiceFields. But I only seem to be able to show Textfields, like Title. How can I show all fields of my ListItem?
The problem is that I get an error when I try to show other fields of a listitem the way I got 'Title' to show, as if the strings I type in don't exist as fields in that listitem. But they do exist and are populated with values!
What is good way to show custom fields of a listitem without getting ObjectReference errors?
Also I get this error: The given key was not present in the dictionary.
private void foo()
{
using (ClientContext context = new ClientContext(ApplicationContext.Current.Url))
{
_list = context.Web.Lists.GetByTitle("MyList").Title);
_items = _list.GetItems(CamlQuery.CreateAllItemsQuery());
context.Load(_items);
context.ExecuteQueryAsync(
new ClientRequestSucceededEventHandler(OnListItemsRequestSucceeded),
new ClientRequestFailedEventHandler(OnListItemsRequestFailed));
}
}
private void OnListItemsRequestSucceeded(Object sender, ClientRequestSucceededEventArgs args)
{
// this is not called on the UI thread
Dispatcher.BeginInvoke(ShowListItemDetails);
}
public void ShowListItemDetails()
{
foreach (ListItem i in _items)
{
TextBox_Details.Text += i["Title"].ToString() + Environment.NewLine;
// Now the rest of the fields of this item.
}
}
Edit: What also is a big problem is I cant get the debugger working. This code is running as a Silverlight webpart on a local Sharepoint site. I attach the debugger to the iexplorer.exe but it won't break.
If I could get the debugger to work it would be a great help indeed.
you have tell the query what all fields you need to pull from lists
CamlQuery camlQuery = new CamlQuery();
camlQuery.ListItemCollectionPosition = itemPosition;
camlQuery.ViewXml =
#"<View>
<ViewFields>
<FieldRef Name='Title'/>
<FieldRef Name='Category'/>
<FieldRef Name='Estimate'/>
</ViewFields>
<RowLimit>10</RowLimit>
</View>";
ListItemCollection listItems = list.GetItems(camlQuery);
clientContext.Load(listItems);
clientContext.ExecuteQuery();
for more details
http://msdn.microsoft.com/en-us/library/ee857094.aspx#SP2010ClientOM_Accessing_Large_Lists
To get item properties you will need to specify all the item properties you need in the second parameter of the ClientContext.Load method
e.g
string server = "http://localhost";
ClientContext context = new ClientContext(server);
Web web = context.Web;
var spList = web.Lists.GetByTitle("MyTitle");
CamlQuery query = new CamlQuery();
var items = spList.GetItems(query);
context.Load(items,
itema => itema.Include(
item => item,
item => item["ComplexProperty"]));
context.ExecuteQuery();`

Resources