System.ArgumentException: 'Cannot bind to the property 'Value' on the target control - binding

I have developped light UserControl with some properties that support binding Like that
public class EditDateTimeBox : UserControl,IKeyboardNavigation
{
private TextBox textBox;
private MonthCalendar monthCalendar = new MonthCalendar();
ToolStripDropDown popup = new ToolStripDropDown();
ToolStripControlHost host;
//.....
[Bindable(true)]
public DateTime Value{get;set;}
}
but whene i try to bind it like that:
bool _binded = false;
string _dataColumn ;
[Category("OverB")]
[Browsable(true)]
public string DataColumn
{
get
{
return _dataColumn;
}
set
{
_dataColumn = value;
if (!_binded && !string.IsNullOrEmpty(_dataColumn) && _dataSource != null)
{
this.DataBindings.Add("Value", DataSource, _dataColumn,true);
_binded = true;
}
}
}
an error thrown say:
System.ArgumentException: 'Cannot bind to the property 'Value' on the target control
when i debug with dotnet support, i found that the Binding class(System.Windows.Forms) in the ChechBinding() method cause the problem
here is the code with comment
// If the control is being inherited, then get the properties for
// the control's type rather than for the control itself. Getting
// properties for the control will merge the control's properties with
// those of its designer. Normally we want that, but for
// inherited controls we don't because an inherited control should
// "act" like a runtime control.
//
InheritanceAttribute attr = (InheritanceAttribute)TypeDescriptor.GetAttributes(control)[typeof(InheritanceAttribute)];
if (attr != null && attr.InheritanceLevel != InheritanceLevel.NotInherited) {
propInfos = TypeDescriptor.GetProperties(controlClass);
}
else {
propInfos = TypeDescriptor.GetProperties(control);
}
for (int i = 0; i < propInfos.Count; i++) {
if(tempPropInfo==null && String.Equals (propInfos[i].Name, propertyName, StringComparison.OrdinalIgnoreCase)) {
tempPropInfo = propInfos[i];
if (tempPropIsNullInfo != null)
break;
}
if(tempPropIsNullInfo == null && String.Equals (propInfos[i].Name, propertyNameIsNull, StringComparison.OrdinalIgnoreCase)) {
tempPropIsNullInfo = propInfos[i];
if (tempPropInfo != null)
break;
}
}
if (tempPropInfo == null) {
throw new ArgumentException(SR.GetString(SR.ListBindingBindProperty, propertyName), "PropertyName");
Any idea?

sorry, i found the problem, the error is purly mine, here is the zomby code
public new ControlBindingsCollection DataBindings { get { return textBox.DataBindings; } }
sorry

Related

How does one end a function in dart similar to in JS typing return

In Javascript when I want to end a function I usually write return, but in the dart, if I do that then the function asks for a return statement at the end of each branch which is messy.
Function createCategory(File image) {
String title = _categoryTitle.value;
if(image == null || title == null || title.length == 0) {
return null;
}
CategoryModel newCategory = new CategoryModel();
if(_categories.value == null) {
_categories.sink.add([newCategory]);
}
return null;
}
What is the correct way to do this in dart?
I think your confusion comes from that your method is valid Dart code but does not really do what I guess you think. Your method has the following signature:
Function createCategory(File image) {
This means your method is named createCategory, takes one argument of the type File and returns a Function. Since you have marked the method to return a Function, then Dart will tell you it is a problem if you just return; since this is properly not what you wanted.
If your method is not going to return any value, then you want to mark this with the return type of void like:
void createCategory(File image) {
String title = _categoryTitle.value;
if (image == null || title == null || title.length == 0) {
return;
}
CategoryModel newCategory = new CategoryModel();
if (_categories.value == null) {
_categories.sink.add([newCategory]);
}
return;
}
I should note, that the last return can be skipped since Dart will automatically add return; at the end of a function if it is missing.
you can do that like this:
void createCategory(File image) {
String title = _categoryTitle.value;
if (image != null && title.isNotEmpty && _categories.value == null) {
_categories.sink.add([CategoryModel()]);
}
}

How can I handle error as Value cannot be null. Parameter name: source

My below view code in View is below
#{
ViewBag.Title = "Student Dashboard";
var StudentRequestTimedt = ViewBag.StudentRequestTime as DataTable;
if (StudentRequestTimedt != null)
{
var StudentRequestTime = StudentRequestTimedt.AsEnumerable().Select(t => new
{
StudentRequestId = t.Field<int>("StudentRequestId"),
FromTime = t.Field<string>("FromTime"),
ToTime = t.Field<string>("ToTime"),
}).ToList();
}
else
{ var StudentRequestTime = ""; }
}
if (StudentRequestTime != "")
{
var StudentRequestTimecount = StudentRequestTime.Where(d => d.StudentRequestId == StudentRequestId).ToList();
}
On writting this I am getting error as StudentRequestTime doesnot exist in the current context.
This issue comes in case I am returning ViewBag.StudentRequestTime as null from controller side
My controller side code is as
if (GetData.Tables[1].Rows.Count > 0 && GetData.Tables[0].Rows.Count > 0)
{
ViewBag.StudentRequestTime = GetData.Tables[1];
}
else
{
ViewBag.StudentRequestTime = null;
}
return View();
Please Also review this below image, Here I am getting data in multiple viewbag in this case how can I manage? var StudentRequestTime is null or empty
How can I handle this issue ?
Updated code resolved my issue
Old code of controller
if (GetData.Tables[1].Rows.Count > 0 && GetData.Tables[0].Rows.Count > 0)
{
ViewBag.StudentRequestTime = GetData.Tables[1];
}
else
{
ViewBag.StudentRequestTime = null;
}
return View();
New Code of controller
ViewBag.StudentRequestTime = GetData.Tables[1];
On ViewSide
Consider this example:
if (eyeColor == EyeColor.Green)
{
// greenEyeColorFound has been declared *in this if statement*,
// so it only exists *within this if statement*
var greenEyeColorFound = true;
}
// this will fail. greenEyeColorFound was declared *in the first if statement*,
// how can the if statement below be aware of it's existence?
if (greenEyeColorFound == true)
{
Debug.WriteLine("Found a person with green eyes!");
}
greenEyeColorFound is locally scoped to the first if statement. Only code within that if statement can be aware of it's existence.
To get my example to work, greenEyeColorFound should be accessible by both ifs, which can be achieved by placing it's declaration outside of both ifs:
// this is now declared *outside* of the two if statements,
// so both are now aware of it and can access it's value.
var greenEyeColorFound = false;
if (eyeColor == EyeColor.Green)
{
greenEyeColorFound = true;
}
// presto, this now works
if (greenEyeColorFound == true)
{
Debug.WriteLine("Found a person with green eyes!");
}
This is the exact issue you are having with StudentRequestTime. Declare it once outside of the ifs, then just set it's value in your if/else statements.
Since we're at it, I wouldn't use ViewBag at all, let alone have it carry DataTables over to the Razor side. I would use viewmodels (read "Accessing Your Model's Data from a Controller" over at Microsoft ASP.NET MVC docs to see how this works, in particular section "Strongly Typed Models and the #model Keyword") which are much cleaner and maintainable.
You can easily refactor your existing code to use viewmodels using the steps below:
1) Create a class, let's name it StudentRequestTimeViewModel:
public class StudentRequestTimeViewModel
{
public int StudentRequestId { get; set; }
public string FromTime { get; set; }
public string ToTime { get; set; }
}
2) In your controller, populate a List<StudentRequestTimeViewModel>:
var studentRequestTimes = new List<StudentRequestTimeViewModel>();
if (GetData.Tables[1].Rows.Count > 0 && GetData.Tables[0].Rows.Count > 0)
{
// populate studentRequestTimes here
}
// return the view, passing in studentRequestTimes as our model
return View(studentRequestTimes);
3) Your Razor then becomes:
/* your model is declared as "#model",
but is accessed as "Model". */
#model List<StudentRequestTimeViewModel>
#if (Model != null && Model.Count > 0)
{
/* your List<StudentRequestTimeViewModel> Model is not null or empty */
foreach(var studentRequestTime in Model)
{
<p>Student with ID #studentRequestTime.StudentRequestId is here.</p>
}
}
else
{
/* your List<StudentRequestTimeViewModel> Model is null or empty */
}

EF modify entity in a function

// Inside an action result
tp = dbContext.tp.Single(x => ...);
foreach (Sample sample in tp.samples)
{
if (sample.SampleStatusId == 1)
changeSamplestatus(sample, 2, now); //change samples to on hold
}
dbContext.SaveChanges();
public void changeSamplestatus(Sample sample, int sampleStatus, DateTime now)
{
sample.SampleHistory.Add(new SampleHistory
{
OldStatus = sample.SampleStatusId,
NewStatus = sampleStatus,
});
sample.SampleStatusId = sampleStatus;
}
I have an entity (sample) that I would like to change it status.
I am calling a function to do so, but the entity doesn't get modified (but it is creating a new row in history table with the correct FK).
It doesn't throw any errors when SaveChanges is called. It just doesn't modify the entity.
You can try:
//INSIDE AN ACTION RESULT
var tp = dbContext.tp.SingleOrDefault(x => ...);
if (tp != null)
{
foreach (Sample sample in tp.samples)
{
if (sample.SampleStatusId == 1)
changeSamplestatus(sample, 2, DateTime.Now);
}
int flag = dbContext.SaveChanges();
if (flag > 0)
{
// update successful
}
}
public void changeSamplestatus(Sample sample, int sampleStatus, DateTime now)
{
//sample.SampleHistory.Add(new SampleHistory
//{
// OldStatus = sample.SampleStatusId,
// NewStatus = sampleStatus,
//});
sample.SampleStatusId = sampleStatus;
}
Don't use Single for this case, because it would throw exception if no result was found or there were more than 1 result. Use SingleOrDefault or FirstOrDefault instead.
You can try this . I hope thiw will work . The Idea is to get the history records first in the context and then update the propterties and set state to mofifed . Please try I didnt tested it but it should work.
public void changeSamplestatus(Sample sample, int sampleStatus, DateTime now)
{
var historyRecordToUpdate = db.SampleHistory.FirstOrDefault(h=>h.id == sampleHistoryId )
if(historyRecordToUpdate !=null )
{
db.Entry(sample).State= EntityState.Modified;
sample.SampleStatusId = sampleStatus;
}
}

TinyIoC Returning Same instance

I am new to the dependency injection pattern and I am having issues getting a new instance of a class from container.Resolve in tinyioc it just keeps returning the same instance rather than a new instance. Now for the code
public abstract class HObjectBase : Object
{
private string _name = String.Empty;
public string Name
{
get
{
return this._name;
}
set
{
if (this._name == string.Empty && value.Length > 0 && value != String.Empty)
this._name = value;
else if (value.Length < 1 && value == String.Empty)
throw new FieldAccessException("Objects names cannot be blank");
else
throw new FieldAccessException("Once the internal name of an object has been set it cannot be changed");
}
}
private Guid _id = new Guid();
public Guid Id
{
get
{
return this._id;
}
set
{
if (this._id == new Guid())
this._id = value;
else
throw new FieldAccessException("Once the internal id of an object has been set it cannot be changed");
}
}
private HObjectBase _parent = null;
public HObjectBase Parent
{
get
{
return this._parent;
}
set
{
if (this._parent == null)
this._parent = value;
else
throw new FieldAccessException("Once the parent of an object has been set it cannot be changed");
}
}
}
public abstract class HZoneBase : HObjectBase
{
public new HObjectBase Parent
{
get
{
return base.Parent;
}
set
{
if (value == null || value.GetType() == typeof(HZoneBase))
{
base.Parent = value;
}
else
{
throw new FieldAccessException("Zones may only have other zones as parents");
}
}
}
private IHMetaDataStore _store;
public HZoneBase(IHMetaDataStore store)
{
this._store = store;
}
public void Save()
{
this._store.SaveZone(this);
}
}
And the derived class is a dummy at the moment but here it is
public class HZone : HZoneBase
{
public HZone(IHMetaDataStore store)
: base(store)
{
}
}
Now since this is meant to be an external library I have a faced class for accessing
everything
public class Hadrian
{
private TinyIoCContainer _container;
public Hadrian(IHMetaDataStore store)
{
this._container = new TinyIoCContainer();
this._container.Register(store);
this._container.AutoRegister();
}
public HZoneBase NewZone()
{
return _container.Resolve<HZoneBase>();
}
public HZoneBase GetZone(Guid id)
{
var metadataStore = this._container.Resolve<IHMetaDataStore>();
return metadataStore.GetZone(id);
}
public List<HZoneBase> ListRootZones()
{
var metadataStore = this._container.Resolve<IHMetaDataStore>();
return metadataStore.ListRootZones();
}
}
However the test is failing because the GetNewZone() method on the Hadrian class keeps returning the same instance.
Test Code
[Fact]
public void ListZones()
{
Hadrian instance = new Hadrian(new MemoryMetaDataStore());
Guid[] guids = { Guid.NewGuid(), Guid.NewGuid(), Guid.NewGuid() };
int cnt = 0;
foreach (Guid guid in guids)
{
HZone zone = (HZone)instance.NewZone();
zone.Id = guids[cnt];
zone.Name = "Testing" + cnt.ToString();
zone.Parent = null;
zone.Save();
cnt++;
}
cnt = 0;
foreach (HZone zone in instance.ListRootZones())
{
Assert.Equal(zone.Id, guids[cnt]);
Assert.Equal(zone.Name, "Testing" + cnt.ToString());
Assert.Equal(zone.Parent, null);
}
}
I know its probably something simple I'm missing with the pattern but I'm not sure, any help would be appreciated.
First, please always simplify the code to what is absolutely necessary to demonstrate the problem, but provide enough that it will actually run; I had to guess what MemoryMetaDataStore does and implement it myself to run the code.
Also, please say where and how stuff fails, to point others straight to the issue. I spent a few minues figuring out that the exception I was getting was your problem and you weren't even getting to the assertions.
That said, container.Resolve<HZoneBase>() will always return the same instance because that's how autoregistration in TinyIoC works - once an abstraction has been resolved, the same instance is always returned for subsequent calls.
To change this, add the following line to the Hadrian constructor:
this._container.Register<HZoneBase, HZone>().AsMultiInstance();
This will tell the container to create a new instance for each resolution request for HZoneBase.
Also, Bassetassen's answer about the Assert part is correct.
In general, if you want to learn DI, you should read Mark Seemann's excellent book "Dependency Injection in .NET" - not quite an easy read as the whole topic is inherently complex, but it's more than worth it and will let you get into it a few years faster than by learning it on your own.
In your assert stage you are not incrementing cnt. You are also using the actual value as the expected one in the assert. This will be confusing, becuase it says something is excpected when it actually is the actual value that is returned.
The assert part should be:
cnt = 0;
foreach (HZone zone in instance.ListRootZones())
{
Assert.Equal(guids[cnt], zone.Id);
Assert.Equal("Testing" + cnt.ToString(), zone.Name);
Assert.Equal(null, zone.Parent);
cnt++;
}

Reflection + Entity Framework to update data in MVC app

I've got a complex form on a page that is bound to a POCO representing a rather complex entity. One of the requirements is that, on blur, I update the database.
I'm currently passing the property (as key), value, and CampaignId via ajax. The key might look something like: Campaign.FanSettings.SocialSharing.FacebookLinkText.
I am using the code below, and getting "close". My final propertyToSet is the FacebookLinkText is not being set, because my object source is of type Entities.Campaign, while my object value is simply a string. I understand these need to be the same type, but I don't understand how to do that. Two questions:
How do I modify the code below to be able to execute the propertyToSet.SetValue method
Since I'm casting this to an object, I don't see how this would actually update my entity, so when I call SaveChanges it updates appropriately. What am I missing?
Thanks!
Code:
public void UpdateCampaign(int id, string key, string value)
{
using (var context = new BetaEntities())
{
var camp = context.Campaigns.Where(e => e.Id == id).Single();
SetProperty(camp, key,value);
}
}
public void SetProperty(object source, string property, object value)
{
string[] bits = property.Split('.');
for (int i = 0; i < bits.Length - 1; i++)
{
PropertyInfo prop = source.GetType().GetProperty(bits[i]);
source = prop.GetValue(source, null);
}
PropertyInfo propertyToSet = null;
if (source is IEnumerable)
{
foreach (object o in (source as IEnumerable))
{
propertyToSet = o.GetType().GetProperty(bits[bits.Length - 1]);
break;
}
}
else
{
propertyToSet = source.GetType().GetProperty(bits[bits.Length - 1]);
}
propertyToSet.SetValue(source, value, null);
}
Solved.
public void UpdateCampaign(int id, string key, string value)
{
using (var context = new BetaEntities())
{
var camp = context.Campaigns.Where(e => e.Id == id).Single();
SetProperty(camp, key, value);
context.SaveChanges()
}
}
public void SetProperty(object source, string property, object value)
{
string[] bits = property.Split('.');
for (int i = 0; i < bits.Length - 1; i++)
{
PropertyInfo prop = source.GetType().GetProperty(bits[i]);
source = prop.GetValue(source, null);
}
PropertyInfo propertyToSet = null;
if (source is IEnumerable)
{
foreach (object o in (source as IEnumerable))
{
propertyToSet = o.GetType().GetProperty(bits[bits.Length - 1]);
propertyToSet.SetValue(o, value,null);
break;
}
}
else
{
propertyToSet = source.GetType().GetProperty(bits[bits.Length - 1]);
propertyToSet.SetValue(source, value, null);
}
}

Resources