Ошибка value cannot be null parameter name value

I am trying to load data of a user edit it and then save it. this has been working and im not quite sure what i changed but now i am getting the following error…

Value cannot be null.
Parameter name: value

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. 

Exception Details: System.ArgumentNullException: Value cannot be null.
Parameter name: value

Source Error: 

An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.

Stack Trace: 


[ArgumentNullException: Value cannot be null.
Parameter name: value]
   System.ComponentModel.DataAnnotations.ValidationContext.set_DisplayName(String value) +51903
   System.Web.Mvc.<Validate>d__1.MoveNext() +135
   System.Web.Mvc.<Validate>d__5.MoveNext() +318
   System.Web.Mvc.DefaultModelBinder.OnModelUpdated(ControllerContext controllerContext, ModelBindingContext bindingContext) +139
   System.Web.Mvc.DefaultModelBinder.BindComplexElementalModel(ControllerContext controllerContext, ModelBindingContext bindingContext, Object model) +66
   System.Web.Mvc.DefaultModelBinder.BindComplexModel(ControllerContext controllerContext, ModelBindingContext bindingContext) +1367
   System.Web.Mvc.DefaultModelBinder.BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) +449
   System.Web.Mvc.ControllerActionInvoker.GetParameterValue(ControllerContext controllerContext, ParameterDescriptor parameterDescriptor) +317
   System.Web.Mvc.ControllerActionInvoker.GetParameterValues(ControllerContext controllerContext, ActionDescriptor actionDescriptor) +117
   System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext controllerContext, String actionName) +343
   System.Web.Mvc.Controller.ExecuteCore() +116
   System.Web.Mvc.ControllerBase.Execute(RequestContext requestContext) +97
   System.Web.Mvc.ControllerBase.System.Web.Mvc.IController.Execute(RequestContext requestContext) +10
   System.Web.Mvc.<>c__DisplayClassb.<BeginProcessRequest>b__5() +37
   System.Web.Mvc.Async.<>c__DisplayClass1.<MakeVoidDelegate>b__0() +21
   System.Web.Mvc.Async.<>c__DisplayClass8`1.<BeginSynchronous>b__7(IAsyncResult _) +12
   System.Web.Mvc.Async.WrappedAsyncResult`1.End() +62
   System.Web.Mvc.<>c__DisplayClasse.<EndProcessRequest>b__d() +50
   System.Web.Mvc.SecurityUtil.<GetCallInAppTrustThunk>b__0(Action f) +7
   System.Web.Mvc.SecurityUtil.ProcessInApplicationTrust(Action action) +22
   System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +60
   System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +9
   System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +8897857
   System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +184


     public ActionResult EditDetails()
    {
        int id = Convert.ToInt32(Session["user"]);
        S1_Customers u1_users = storeDB.S1_Customers.Find(id);
        return View(u1_users);
    }

    [HttpPost]
    public ActionResult EditDetails(S1_Customers u1_users)
    {
        var Pcode = "";  
        if (ModelState.IsValid)
        {

I am not even reaching ModelState.IsValid when i click submit

asked Sep 21, 2011 at 13:07

Beginner's user avatar

1

Did you change any names? The form names have to map 1-1 with your Action parameters. In this case, the «name» parameter was not passed to the controller action, so it is null.

Wild guess, need more information (method signature of action)

answered Sep 21, 2011 at 13:10

Daryl Teo's user avatar

Daryl TeoDaryl Teo

5,3641 gold badge30 silver badges37 bronze badges

6

You’ll receive that error if you have some properties decorated by DisplayAttribute with empty Name
([DisplayAttribute(Name = "", Description = "Any description")])

Community's user avatar

answered Jun 20, 2013 at 11:52

Aleksandr Belevtsov's user avatar

1

If you use [Display(Name=»»)] as for properties of your model, This will cause the error you get. To solve this problem, you should avoid using empty display name attribute.

[Display(Name = "")] //this line is the cause of error
public string PromotionCode { get; set; }

answered Apr 9, 2014 at 14:12

Arkadas Kilic's user avatar

Arkadas KilicArkadas Kilic

2,4162 gold badges20 silver badges16 bronze badges

It could most probably be that your model has a property that returns a non-nullable value, like int, DateTime, double etc. And if user is updating the entry you are probably not storing that value in a hidden field or somewhere, so when the data is returned that particular property is null. Either place that property into a hidden field or make your property nullable in a model by changing int to int?, etc.

answered Sep 21, 2011 at 13:12

Huske's user avatar

HuskeHuske

9,1562 gold badges35 silver badges52 bronze badges

1

I was getting this same error message when manually setting a @Html.TextArea, I had used the code from an @Html.TextBox(null, this.Model) in an EditorTemplate and when I did @Html.TextArea(null, this.Model) I got the error above.

Turns out you have to do @Html.TextArea("", this.Model) and it works.

Stephen Rauch's user avatar

Stephen Rauch

47.5k31 gold badges106 silver badges135 bronze badges

answered Apr 14, 2018 at 1:56

Aaron's user avatar

AaronAaron

311 silver badge3 bronze badges

  • Remove From My Forums
  • Question

  • Need some advice to reslove the error«value cannot be null. parameter name»

    private ObservableCollection<Sp> splitSp;
    
     public ObservableCollection<Sp> SplitSp
            {
                get
                {
                    if (this.splitSp == null)
                        this.splitSp = new ObservableCollection<Sp>();
                    return this.splitSp;
                }
                set
                {
                    if (this.splitSp != value)
                    {
                        this.splitSp = value;
                        this.OnPropertyChanged("SplitSp");
                    }
                }
            }

    It throws the exception on the last line.But when I check the

    splitSp and value

    they are not null.

    The base class is

     public class NotifyBase : INotifyPropertyChanged
        {
            public event PropertyChangedEventHandler PropertyChanged;
    
            protected void OnPropertyChanged(String name)
            {
                if (this.PropertyChanged != null)
                {
                    this.PropertyChanged(this, new PropertyChangedEventArgs(name));
                }
            }
        }

Answers

  • I find the error by myself. In my xaml file, one of binding property name was misspelled. Maybe the code could not find the property.

    • Marked as answer by

      Monday, September 19, 2016 7:51 PM

    • Edited by
      HZ.USA
      Monday, September 19, 2016 7:51 PM

// This file contains your Data Connector logic
section GitHub;

redirect_uri = "https://oauth.powerbi.com/views/oauthredirect.html";
client_id = "";
client_secret = "";
windowWidth = 1000;
windowHeight = 800;


[DataSource.Kind="GitHub", Publish="GitHub.Publish"]
shared GitHub.Contents = (optional message as text) =>
    let
        _message = if (message <> null) then message else "(no message)",
        a = "Hello from GitHub: " & _message
    in
        a;

// Data Source Kind description
GitHub = [
    Authentication = [
        OAuth = [
            StartLogin = StartLogin,
            FinishLogin = FinishLogin
        ]
    ],
    Label = Extension.LoadString("DataSourceLabel")
];

StartLogin = (resourceUrl, state, display) =>
        let
            TestConnection = (url) => {"GitHub.Contents"},
            AuthorizeUrl = "https://Github.com/login/oauth/authorize?" & Uri.BuildQueryString([
                client_id = client_id,
                scope = "user, repo",
                state = state,
                redirect_uri = redirect_uri])
        in
            [
                LoginUri = AuthorizeUrl,
                CallbackUri = redirect_uri,
                WindowHeight = windowHeight,
                WindowWidth = windowWidth,
                Context = null
            ];

FinishLogin = (context, callbackUri, state) =>
    let
        Parts = Uri.Parts(callbackUri)[Query]
    in
        TokenMethod(Parts[code]);

 TokenMethod = (code) =>
    let
        Response = Web.Contents("https://Github.com/login/oauth/access_token", [
            Content = Text.ToBinary(Uri.BuildQueryString([
                client_id = client_id,
                client_secret = client_secret,
                code = code,
                redirect_uri = redirect_uri])),
            Headers=[#"Content-type" = "application/x-www-form-urlencoded",#"Accept" = "application/json"]]),
        Parts = Json.Document(Response)
    in
        Parts;

// Data Source UI publishing description
GitHub.Publish = [
    Beta = true,
    Category = "Other",
    ButtonText = { Extension.LoadString("ButtonTitle"), Extension.LoadString("ButtonHelp") },
    LearnMoreUrl = "https://powerbi.microsoft.com/",
    SourceImage = GitHub.Icons,
    SourceTypeImage = GitHub.Icons
];

GitHub.Icons = [
    Icon16 = { Extension.Contents("GitHub16.png"), Extension.Contents("GitHub20.png"), Extension.Contents("GitHub24.png"), Extension.Contents("GitHub32.png") },
    Icon32 = { Extension.Contents("GitHub32.png"), Extension.Contents("GitHub40.png"), Extension.Contents("GitHub48.png"), Extension.Contents("GitHub64.png") }
];
  • Remove From My Forums
  • Question

  • What could be problem?

    When I open VS2008, I get Error box «Value Cannot be be null. Parameter name: name» and I see a Report Design in backgroud. (this reports have no parameter at all)

    We have been developing SQL Server 2008R2 SSRS reports.

    I have several reports in this VS Solution. Some of the reports do have parameters and they are cascading parameters.

    All reports looks good despite Value cannot be null error.


    Kenny_I

Answers

    • Marked as answer by

      Monday, June 17, 2013 1:52 AM

I am trying to load data of a user edit it and then save it. this has been working and im not quite sure what i changed but now i am getting the following error…

Value cannot be null.
Parameter name: value

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. 

Exception Details: System.ArgumentNullException: Value cannot be null.
Parameter name: value

Source Error: 

An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.

Stack Trace: 


[ArgumentNullException: Value cannot be null.
Parameter name: value]
   System.ComponentModel.DataAnnotations.ValidationContext.set_DisplayName(String value) +51903
   System.Web.Mvc.<Validate>d__1.MoveNext() +135
   System.Web.Mvc.<Validate>d__5.MoveNext() +318
   System.Web.Mvc.DefaultModelBinder.OnModelUpdated(ControllerContext controllerContext, ModelBindingContext bindingContext) +139
   System.Web.Mvc.DefaultModelBinder.BindComplexElementalModel(ControllerContext controllerContext, ModelBindingContext bindingContext, Object model) +66
   System.Web.Mvc.DefaultModelBinder.BindComplexModel(ControllerContext controllerContext, ModelBindingContext bindingContext) +1367
   System.Web.Mvc.DefaultModelBinder.BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) +449
   System.Web.Mvc.ControllerActionInvoker.GetParameterValue(ControllerContext controllerContext, ParameterDescriptor parameterDescriptor) +317
   System.Web.Mvc.ControllerActionInvoker.GetParameterValues(ControllerContext controllerContext, ActionDescriptor actionDescriptor) +117
   System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext controllerContext, String actionName) +343
   System.Web.Mvc.Controller.ExecuteCore() +116
   System.Web.Mvc.ControllerBase.Execute(RequestContext requestContext) +97
   System.Web.Mvc.ControllerBase.System.Web.Mvc.IController.Execute(RequestContext requestContext) +10
   System.Web.Mvc.<>c__DisplayClassb.<BeginProcessRequest>b__5() +37
   System.Web.Mvc.Async.<>c__DisplayClass1.<MakeVoidDelegate>b__0() +21
   System.Web.Mvc.Async.<>c__DisplayClass8`1.<BeginSynchronous>b__7(IAsyncResult _) +12
   System.Web.Mvc.Async.WrappedAsyncResult`1.End() +62
   System.Web.Mvc.<>c__DisplayClasse.<EndProcessRequest>b__d() +50
   System.Web.Mvc.SecurityUtil.<GetCallInAppTrustThunk>b__0(Action f) +7
   System.Web.Mvc.SecurityUtil.ProcessInApplicationTrust(Action action) +22
   System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +60
   System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +9
   System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +8897857
   System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +184


     public ActionResult EditDetails()
    {
        int id = Convert.ToInt32(Session["user"]);
        S1_Customers u1_users = storeDB.S1_Customers.Find(id);
        return View(u1_users);
    }

    [HttpPost]
    public ActionResult EditDetails(S1_Customers u1_users)
    {
        var Pcode = "";  
        if (ModelState.IsValid)
        {

I am not even reaching ModelState.IsValid when i click submit

asked Sep 21, 2011 at 13:07

Beginner's user avatar

1

Did you change any names? The form names have to map 1-1 with your Action parameters. In this case, the «name» parameter was not passed to the controller action, so it is null.

Wild guess, need more information (method signature of action)

answered Sep 21, 2011 at 13:10

Daryl Teo's user avatar

Daryl TeoDaryl Teo

5,2241 gold badge30 silver badges36 bronze badges

6

You’ll receive that error if you have some properties decorated by DisplayAttribute with empty Name
([DisplayAttribute(Name = "", Description = "Any description")])

Community's user avatar

answered Jun 20, 2013 at 11:52

Aleksandr Belevtsov's user avatar

1

If you use [Display(Name=»»)] as for properties of your model, This will cause the error you get. To solve this problem, you should avoid using empty display name attribute.

[Display(Name = "")] //this line is the cause of error
public string PromotionCode { get; set; }

answered Apr 9, 2014 at 14:12

Arkadas Kilic's user avatar

Arkadas KilicArkadas Kilic

2,3902 gold badges19 silver badges16 bronze badges

It could most probably be that your model has a property that returns a non-nullable value, like int, DateTime, double etc. And if user is updating the entry you are probably not storing that value in a hidden field or somewhere, so when the data is returned that particular property is null. Either place that property into a hidden field or make your property nullable in a model by changing int to int?, etc.

answered Sep 21, 2011 at 13:12

Huske's user avatar

HuskeHuske

9,0852 gold badges35 silver badges52 bronze badges

I was getting this same error message when manually setting a @Html.TextArea, I had used the code from an @Html.TextBox(null, this.Model) in an EditorTemplate and when I did @Html.TextArea(null, this.Model) I got the error above.

Turns out you have to do @Html.TextArea("", this.Model) and it works.

Stephen Rauch's user avatar

Stephen Rauch

46.6k31 gold badges109 silver badges131 bronze badges

answered Apr 14, 2018 at 1:56

Aaron's user avatar

AaronAaron

112 silver badges2 bronze badges

0 / 0 / 0

Регистрация: 20.04.2012

Сообщений: 25

1

20.07.2012, 12:40. Показов 38140. Ответов 6


Хочу разобраться в разработке приложений под Windows Phone. Поставил все необходимое, но при создании нового WindowsPhoneApplication открыть файл MainPage.xaml выдает ошибочку в левом окошке:

System.ArgumentNullException
Value cannot be null.
Parameter name: parentContext
at Microsoft.Windows.Design.Metadata.ReflectionMetada taContext..ctor(IMetadataContext parentContext)
at MS.Internal.Host.ProjectMetadataContext..ctor(IMet adataContext platformMetadata, AssemblyReferenceProvider referenceProvider)
at MS.Internal.Host.ProjectMetadataContext.FromRefere nces(AssemblyReferenceProvider referenceProvider)
at MS.Internal.Designer.VSDesigner.GetMetadataForDesi gnerContext(DesignerContext designerContext)
at MS.Internal.Host.PersistenceSubsystem.Load()
at MS.Internal.Host.Designer.Load()
at MS.Internal.Designer.VSDesigner.Load()
at MS.Internal.Designer.VSIsolatedDesigner.VSIsolated View.Load()
at MS.Internal.Designer.VSIsolatedDesigner.VSIsolated DesignerFactory.Load(IsolatedView view)
at MS.Internal.Host.Isolation.IsolatedDesigner.Bootst rapProxy.LoadDesigner(IsolatedDesignerFactory factory, IsolatedView view)
at MS.Internal.Host.Isolation.IsolatedDesigner.Bootst rapProxy.LoadDesigner(IsolatedDesignerFactory factory, IsolatedView view)
at MS.Internal.Host.Isolation.IsolatedDesigner.Load()
at MS.Internal.Designer.DesignerPane.LoadDesignerView ()

__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь

0

Programming

Эксперт

94731 / 64177 / 26122

Регистрация: 12.04.2006

Сообщений: 116,782

20.07.2012, 12:40

Ответы с готовыми решениями:

Получаю ошибку «object» не содержит определения для «ID»
Здравствуйте! Делаю простенький пример, для понимания, как работает вся эта кухня в ASP.NET MVC,…

Выдает ошибку в строке с if (f = fopen_s(«FB.txt», «wb») == NULL)
Выдает оошибку в строке с if ((f = fopen_s(&quot;FB.txt&quot;, &quot;wb&quot;)) == NULL)
не понимаю что сделать?????…

Обработка «null» в MS Access «Приведение типа «|DBNull» к типу «String» является недопустимым»
Здравствуйте.
Работаю с базой MS Access
Вывожу в DataGridView таблицу
Проблема следующая, если у…

Циклы, получаю ошибку «list index out of bounds (0)»
Циклы, проблема, получаю ошибку &quot;list index out of bounds (0)&quot;

var
i, j, m:integer;

6

6042 / 3451 / 335

Регистрация: 14.06.2009

Сообщений: 8,136

Записей в блоге: 2

20.07.2012, 13:17

2

Цитата
Сообщение от Nimrod
Посмотреть сообщение

Почему я получаю ошибку «Value cannot be null»?

потому что значение не может быть null, а где-то в коде происходит попытка этот null присвоить

0

0 / 0 / 0

Регистрация: 20.04.2012

Сообщений: 25

20.07.2012, 13:46

 [ТС]

3

Цитата
Сообщение от nio
Посмотреть сообщение

потому что значение не может быть null, а где-то в коде происходит попытка этот null присвоить

мощный ответ, осталось понять как шибка возникает в новом проекте и как её устранить

0

6042 / 3451 / 335

Регистрация: 14.06.2009

Сообщений: 8,136

Записей в блоге: 2

20.07.2012, 13:50

4

Цитата
Сообщение от Nimrod
Посмотреть сообщение

осталось понять как шибка возникает в новом проекте и как её устранить

а что тут понимать? пошаговое выполнение, точки останова, блоки try-catch

0

428 / 429 / 93

Регистрация: 16.07.2012

Сообщений: 886

20.07.2012, 14:46

5

Цитата
Сообщение от nio
Посмотреть сообщение

а что тут понимать? пошаговое выполнение, точки останова, блоки try-catch

В случае WPF это не так уж просто сделать, если ошибка происходит при создании объектов из XAML где-то во внутренностях системы.

Добавлено через 2 минуты

Цитата
Сообщение от Nimrod
Посмотреть сообщение

Хочу разобраться в разработке приложений под Windows Phone. Поставил все необходимое, но при создании нового WindowsPhoneApplication открыть файл MainPage.xaml выдает ошибочку в левом окошке

Вы ходите сказать, что только что созданный проект (в который вы ни строчки кода не добавили) не компилируется? Или компилируется, но после запуска ошибка вылетает? Или ошибка не во время запуска, а во время редактирования в редакторе?
В общем, попробуйте новый проект создать и посмотреть, будет ли нормально отображаться MainPage.xaml в нем.

0

0 / 0 / 0

Регистрация: 20.04.2012

Сообщений: 25

20.07.2012, 15:22

 [ТС]

6

Цитата
Сообщение от canopen
Посмотреть сообщение

В случае WPF это не так уж просто сделать, если ошибка происходит при создании объектов из XAML где-то во внутренностях системы.

Добавлено через 2 минуты

Вы ходите сказать, что только что созданный проект (в который вы ни строчки кода не добавили) не компилируется? Или компилируется, но после запуска ошибка вылетает? Или ошибка не во время запуска, а во время редактирования в редакторе?
В общем, попробуйте новый проект создать и посмотреть, будет ли нормально отображаться MainPage.xaml в нем.

Именно только что созданный проекта, без строчки моего кода, ошибка не во время запуска, а во время редактирования в редакторе в левом окошке, где должна быть визуальная формочка приложения. Создание нового проекта не решает проблемы.

0

428 / 429 / 93

Регистрация: 16.07.2012

Сообщений: 886

20.07.2012, 15:35

7

Ну это вам надо по конкретной версии IDE в интернете поискать. Visual Studio наверное используете?

Добавлено через 1 минуту
А если в визуальном редакторе не отображается, но компилируется и запускается все нормально, то и вообще плюнуть на визуальный редактор и по-джедайски редактировать XAML вручную. Только полезнее будет )))

0

  • Remove From My Forums
  • Question

  • Need some advice to reslove the error«value cannot be null. parameter name»

    private ObservableCollection<Sp> splitSp;
    
     public ObservableCollection<Sp> SplitSp
            {
                get
                {
                    if (this.splitSp == null)
                        this.splitSp = new ObservableCollection<Sp>();
                    return this.splitSp;
                }
                set
                {
                    if (this.splitSp != value)
                    {
                        this.splitSp = value;
                        this.OnPropertyChanged("SplitSp");
                    }
                }
            }

    It throws the exception on the last line.But when I check the

    splitSp and value

    they are not null.

    The base class is

     public class NotifyBase : INotifyPropertyChanged
        {
            public event PropertyChangedEventHandler PropertyChanged;
    
            protected void OnPropertyChanged(String name)
            {
                if (this.PropertyChanged != null)
                {
                    this.PropertyChanged(this, new PropertyChangedEventArgs(name));
                }
            }
        }

Answers

  • I find the error by myself. In my xaml file, one of binding property name was misspelled. Maybe the code could not find the property.

    • Marked as answer by

      Monday, September 19, 2016 7:51 PM

    • Edited by
      HZ.USA
      Monday, September 19, 2016 7:51 PM

Вопрос:

Я не знаю, почему я получаю такую ​​ошибку. Иногда это происходит, и я подозрительно отношусь к моему коду, который все еще работает с потоком, пока я закрываю приложение. Поэтому, когда я открываю снова, это случается.

Value cannot be null.
Parameter name: source
StackTree :
at System.Linq.Enumerable.Where[TSource](IEnumerable`1 source, Func`2 predicate)
at Susenas2015.ViewModels.Kuesioner.VMVsen15_KVal.SettingValidationAndRange(List`1 listTextBox, List`1 listCheckBox, TabControl tabControl) in d:handitaOfficeProjectSusenas 2015Aplikasi Template SurveiSusenas2015ViewModelsKuesionerVMVsen15_KVal.cs:line 430
at Susenas2015.ViewModels.Kuesioner.VMVsen15_KVal.vSen15_K_Loaded(Object sender, RoutedEventArgs e) in d:handitaOfficeProjectSusenas 2015Aplikasi Template SurveiSusenas2015ViewModelsKuesionerVMVsen15_KVal.cs:line 846
at System.Windows.RoutedEventHandlerInfo.InvokeHandler(Object target, RoutedEventArgs routedEventArgs)
at System.Windows.EventRoute.InvokeHandlersImpl(Object source, RoutedEventArgs args, Boolean reRaised)
at System.Windows.UIElement.RaiseEventImpl(DependencyObject sender, RoutedEventArgs args)
at System.Windows.UIElement.RaiseEvent(RoutedEventArgs e)
at System.Windows.BroadcastEventHelper.BroadcastEvent(DependencyObject root, RoutedEvent routedEvent)
at System.Windows.BroadcastEventHelper.BroadcastLoadedEvent(Object root)
at MS.Internal.LoadedOrUnloadedOperation.DoWork()
at System.Windows.Media.MediaContext.FireLoadedPendingCallbacks()
at System.Windows.Media.MediaContext.FireInvokeOnRenderCallbacks()
at System.Windows.Media.MediaContext.RenderMessageHandlerCore(Object resizedCompositionTarget)
at System.Windows.Media.MediaContext.RenderMessageHandler(Object resizedCompositionTarget)
at System.Windows.Media.MediaContext.Resize(ICompositionTarget resizedCompositionTarget)
at System.Windows.Interop.HwndTarget.OnResize()
at System.Windows.Interop.HwndTarget.HandleMessage(WindowMessage msg, IntPtr wpa`

Мой код здесь

    private void SettingValidationAndRange(List<TextBox> listTextBox, List<CheckBox> listCheckBox, TabControl tabControl)
{

List<string> listNotDeclare = new List<string>();

foreach (var textB in listTextBox)
{
if (textB.Tag != null)
break;

Metadata metadata = ListMetadataKor.Where(
x => "text" + x.Field == textB.Name // this line 430

).FirstOrDefault();

if (metadata == null)
{
if (!string.IsNullOrEmpty(textB.Name))
listNotDeclare.Add(textB.Name);
}
else
{
metadata.TabControl = tabControl;
textB.Tag = metadata;
}

textB.AddEvents();
textB.AutomateFocus();

}

if (listNotDeclare.Count > 0)
{
Clipboard.SetText(string.Join(",", listNotDeclare.ToArray()));
Dialog.Info("Ada beberapa Metadata tidak ditemukan data sudah dicopy ke clipboard");
}

}

Когда я запускаю свое приложение в первый раз, он не получает никаких ошибок. Это происходит, когда я открываю второй или более. И если я открою приложение, оно застряло бы в этом коде.

Как я могу это решить? Я уверен, что мое свойство ListMetadataKor не null

И ListMetadataKor является экземпляром объекта List<Metadata>, который я создал. Это случается только в редких случаях. И я не знаю, чтобы решить это.

UPDATE

Это мой код на картинке enter image description here

Я заполняю ListMetadataKor этим кодом

BWHelper.Run((s, e) =>
{
DataTable dataMetaDataKOR = ExcelHelper.GetDataTableFromExcel(
AppConstants.FILE_METADATA, AppConstants.SHEET_METADATA_KOR
);

DataTable dataKonsistensiKOR = ExcelHelper.GetDataTableFromExcel(
AppConstants.FILE_METADATA, AppConstants.SHEET_KONSISTENSI_KOR
);

listKonsistensiKor = Tools.ToolConvert.GetKonsistensi(dataKonsistensiKOR);
listMetadataKor = Tools.ToolConvert.GetMetadata(dataMetaDataKOR);

foreach (Metadata metadata in listMetadataKor)
{
metadata.Range.ProsesRange();
}

}, (s, e) =>
{
try
{
kor = new VSEN15_K() { Title = "Validasi Susenas - KOR" };
kor.DataContext = new VMVsen15_KVal(rtSusenas.MasterRT, kor, this, listKonsistensiKor, listMetadataKor);
kor.PreviewKeyDown += EventsCollection.EnterAsTabPreviewKeyDown;
vmHome.HideLoading();
UpdateMetaDataEntriKOR(RTSusenas.MasterRT);
kor.ShowDialog();
}
catch (Exception Ex)
{
vmHome.HideLoading();
Dialog.Error(Ex);
}
});

И затем я бросаю переменную через конструктор моего класса

 public VMVsen15_KVal(
MasterRT masterRT,
VSEN15_K vSen15_K,
IDaftarSusenas vmDaftarRTSusenas,
List<Konsistensi> listKonsistensiKor,
List<Metadata> listMetadataKor

)
{

ListArtDetail = new ObservableCollection<ARTDetailVal>();

this.ListKonsistensiKor = listKonsistensiKor;
this.ListMetadataKor = listMetadataKor;

Мои инструменты konsistensi как это

public static List<Konsistensi> GetKonsistensi(DataTable dataTable)
{
List<Konsistensi> listMetadata = new List<Konsistensi>();
for (int i = 0; i < dataTable.Rows.Count; i++)
{
Konsistensi k = new Konsistensi();
object[] required = new object[] { DBNull.Value, "" };
k.Field = dataTable.Rows[i][FIELD].ToString();
if (string.IsNullOrWhiteSpace(k.Field)) continue;
k.Message = dataTable.Rows[i][MESSAGE].ToString();
var obj = dataTable.Rows[i][ORDER];
k.Order = !required.Contains(dataTable.Rows[i][ORDER]) ? Convert.ToInt32(dataTable.Rows[i][ORDER]) : (int?)null;
k.Page = !required.Contains(dataTable.Rows[i][PAGE]) ? Convert.ToInt32(dataTable.Rows[i][PAGE]) : (int?)null;
k.Perlakuan = dataTable.Rows[i][PERLAKUAN].ToString();
k.RelFields = dataTable.Rows[i][RELFIELDS].ToString();
k.Rule = dataTable.Rows[i][RULE].ToString();

if (dataTable.Rows[i][LEVEL].ToString().ToUpper() == ("ART"))
k.LevelKonsistensi = LevelKonsistensi.ART;
else if (dataTable.Rows[i][LEVEL].ToString().ToUpper() == ("RT"))
k.LevelKonsistensi = LevelKonsistensi.RT;
else if (dataTable.Rows[i][LEVEL].ToString().ToUpper() == ("RTWARNING"))
k.LevelKonsistensi = LevelKonsistensi.RTWarning;
else if (dataTable.Rows[i][LEVEL].ToString().ToUpper().Contains("ARTWARNING"))
k.LevelKonsistensi = LevelKonsistensi.ARTWarning;
else
k.LevelKonsistensi = LevelKonsistensi.Lain;

//k.LevelKonsistensi = dataTable.Rows[i][LEVEL].ToString().Contains("ART") ? LevelKonsistensi.ART : LevelKonsistensi.RT;
if (k.IsEmpty())
continue;

listMetadata.Add(k);
}
return listMetadata;
}

Лучший ответ:

В сообщении об ошибке четко указано, что параметр source null. Источник – это перечисляемый вами список. В вашем случае это объект ListMetadataKor. И его определенно null в то время, когда вы его фильтруете второй раз. Убедитесь, что вы никогда не назначали null этому списку. Просто проверьте все ссылки на этот список в коде и найдите назначения.

Ответ №1

  Значение не может быть нулевым. Имя параметра: источник

Выше ошибка возникает в ситуации, когда вы запрашиваете коллекцию, которая является нулевой.

Для демонстрации кода ниже приведено такое исключение.

Console.WriteLine("Hello World");
IEnumerable<int> list = null;
list.Where(d => d ==4).FirstOrDefault();

Вот вывод приведенного выше кода.

Привет, мир Исключение во время выполнения (строка 11): значение не может быть нулевым. Имя параметра: источник

Stack Trace:

[System.ArgumentNullException: значение не может быть нулевым. Имя параметра: источник] в Program.Main(): строка 11

В вашем случае ListMetadataKor является нулевым.
Здесь – скрипка, если вы хотите поиграть.

Ответ №2

Когда вы вызываете оператор Linq следующим образом:

// x = new List<string>();
var count = x.Count(s => s.StartsWith("x"));

Фактически вы используете метод расширения в пространстве имен System.Linq, поэтому компилятор переводит его в:

var count = Enumerable.Count(x, s => s.StartsWith("x"));

Итак, ошибка, которую вы получаете выше, состоит в том, что первый параметр source (который был бы x в примере выше) равен null.

Ответ №3

  System.ArgumentNullException: значение не может быть нулевым. Имя параметра: значение

Это сообщение об ошибке не очень полезно!

Вы можете получить эту ошибку разными способами. Ошибка не всегда может быть связана с именем параметра: значение. Это может быть любое имя параметра, передаваемое в функцию.

В качестве общего способа решения этой проблемы рассмотрим трассировку стека или стек вызовов:

Test method GetApiModel threw exception:
System.ArgumentNullException: Value cannot be null.
Parameter name: value
at Newtonsoft.Json.JsonConvert.DeserializeObject(String value, Type type, JsonSerializerSettings settings)

Вы можете видеть, что имя параметра value является первым параметром для DeserializeObject. Это привело меня к проверке моего сопоставления AutoMapper, где мы десериализовываем строку JSON. Эта строка пуста в моей базе данных.

Вы можете изменить код для проверки на ноль.

Ответ №4

Ниже указана ошибка при экспорте отчетов Crystal в формате Excel.

System.ArgumentNullException: Value cannot be null.
Parameter name: window
at System.Windows.Interop.WindowInteropHelper..ctor(Window window)
at System.Windows.MessageBox.Show(Window owner, String messageBoxText, String caption, MessageBoxButton button, MessageBoxImage icon)
at SAPBusinessObjects.WPF.Viewer.ViewerCore.HandleExceptionEvent(Object eventSource, Exception e, Boolean suppressMessage)
at SAPBusinessObjects.WPF.Viewer.MainReportDocument.Export(ExportRequestContext context, String filePath)
at SAPBusinessObjects.WPF.Viewer.ReportAlbum.<>c__DisplayClass4.<ExportReport>b__3()
at SAPBusinessObjects.WPF.Viewer.DelegateMarshaler.<>c__DisplayClass29.<QueueOnThreadPoolThread>b__28(Object )
at System.Threading.QueueUserWorkItemCallback.WaitCallback_Context(Object state)
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.QueueUserWorkItemCallback.System.Threading.IThreadPoolWorkItem.ExecuteWorkItem()
at System.Threading.ThreadPoolWorkQueue.Dispatch()
at System.Threading._ThreadPoolWaitCallback.PerformWaitCallback()

I’m getting a similar stack trace. The app which I am using is one created with the wizard with just an App.xaml and the MainPage.xaml «Welcome to Xamarin.Forms!» page (I was using it to test something else). I have just changed from iOS to Android and get this error.

@StephaneDelcroix, can this be re-opened, please?

      Module: Ils.dll
        Resource: Ils.App.xaml
          Creating empty App.__InitComponentRuntime
            done.
          Copying body of InitializeComponent to __InitComponentRuntime
            done.
          Parsing Xaml
            done.
          Replacing 0.InitializeComponent ()
            failed.
    App.xaml : error : Value cannot be null.
    App.xaml : error : Parameter name: type
       at Mono.Cecil.Mixin.CheckType(Object type)
       at Mono.Cecil.ModuleDefinition.ImportReference(TypeReference type, IGenericParameterProvider context)
       at Xamarin.Forms.Build.Tasks.ModuleDefinitionExtensions.ImportCtorReference(ModuleDefinition module, TypeReference type, TypeReference[] classArguments, Func`2 predicate)
       at Xamarin.Forms.Build.Tasks.ModuleDefinitionExtensions.ImportCtorReference(ModuleDefinition module, ValueTuple`3 type, Int32 paramCount)
       at Xamarin.Forms.Build.Tasks.XamlCTask.TryCoreCompile(MethodDefinition initComp, MethodDefinition initCompRuntime, ILRootNode rootnode, Exception& exception)
        Resource: Ils.MainPage.xaml
          Creating empty MainPage.__InitComponentRuntime
            done.
          Copying body of InitializeComponent to __InitComponentRuntime
            done.
          Parsing Xaml
            done.
          Replacing 0.InitializeComponent ()
            failed.
    MainPage.xaml : error : Value cannot be null.
    MainPage.xaml : error : Parameter name: type
       at Mono.Cecil.Mixin.CheckType(Object type)
       at Mono.Cecil.ModuleDefinition.ImportReference(TypeReference type, IGenericParameterProvider context)
       at Xamarin.Forms.Build.Tasks.ModuleDefinitionExtensions.ImportCtorReference(ModuleDefinition module, TypeReference type, TypeReference[] classArguments, Func`2 predicate)
       at Xamarin.Forms.Build.Tasks.ModuleDefinitionExtensions.ImportCtorReference(ModuleDefinition module, ValueTuple`3 type, Int32 paramCount)
       at Xamarin.Forms.Build.Tasks.XamlCTask.TryCoreCompile(MethodDefinition initComp, MethodDefinition initCompRuntime, ILRootNode rootnode, Exception& exception)
        Changing the module MVID
          done.
    Writing the assembly
      done.
  Done executing task "XamlCTask" -- FAILED.
Done building target "XamlC" in project "Ils.csproj" -- FAILED.

Visual Studio - parameter instance with value null (and other design errors) when opening XSD files

If you’ve stumbled upon this post it most likely means you’re having issues while trying to open XSD files from Visual Studio 2017 or 2019. More specifically, this problem often happens when you try to open a .xsd file of a rather old project, originally created using the ASP.NET Framework 2.0, 3.5 or so on and then upgraded to ASP.NET 4.x later on.

The error message presented by the Visual Studio GUI is the following:

Value cannot be null. Parameter name: instance

And here’s the stacktrace:

Hide Call Stack at System.ComponentModel.TypeDescriptor.AddAttributes(Object instance, Attribute[] attributes) at Microsoft.VisualStudio.Design.VSDesignSurface.CreateDesigner(IComponent component, Boolean rootDesigner) at System.ComponentModel.Design.DesignerHost.AddToContainerPostProcess(IComponent component, String name, IContainer containerToAddTo) at System.ComponentModel.Design.DesignerHost.PerformAdd(IComponent component, String name) at System.ComponentModel.Design.DesignerHost.Add(IComponent component, String name) at System.ComponentModel.Container.Add(IComponent component) at Microsoft.VSDesigner.DataSource.Designer.DataSourceDesignerLoader.HandleLoad(IDesignerSerializationManager serializationManager) at Microsoft.VSDesigner.DesignerFramework.BaseDesignerLoader.PerformLoad(IDesignerSerializationManager serializationManager) at Microsoft.VSDesigner.DesignerFramework.BaseDesignerLoader.Microsoft.VisualStudio.TextManager.Interop.IVsTextBufferDataEvents.OnLoadCompleted(Int32 fReload)
This seems to be .net 3.5 specific as I opened another project that’s 4.0 and its .xsd opened in designer fine.

Here’s a screenshot showing the error, as shown by the Visual Studio xsd design view/mode:

Visual Studio - parameter instance with value null (and other design errors) when opening XSD files

UPDATE: depending on Visual Studio and .NET Framework, some times the error message can be slightly different, such as:

There is no designer for the class Microsoft.VSDesigner.DataSource.DesignDataSource.

Luckily enough, the workaround is still the same.

The Workaround

At the time of writing (July 2019) there are at least two open issues created to address this problem on the Visual Studio Developer Community website:

  • #26937 — DataSet fails to open in designer
  • #54432 — Opening Dataset xsd’s Throws Designer Error

Despite these feedbacks, there are no official answers — or fixes — released by Microsoft so far.

Luckily enough I was able to find a workaround by mixing two different suggestions taken from two treads on MS Development Network and StackOverflow. The workaround I found works that way:

  • Open the Project (or Website) Property Page.
  • Locate the section where you can choose the .NET Framework version (Start Options -> Build for most project types).
  • If your project is using a .NET Framework lower than 4.7.2, set it to 4.7.2 (in case you don’t have it installed, you might have to download it and restart Visual Studio afterwards).
  • If your project is using the .NET Framework 4.7.2, downgrade it to 4.6.1 (again, if you don’t have it download it and restart Visual Studio).

This should permanently fix your problem and let you open the XSD files in design mode.


Submitted by

Anonymous

on

‎10-19-2018

03:04 AM

Hi, I have this error appearing when I try to load the data. I started to get it after I updated PBI Desktop to the latest version. Before it was working fine. Please, help me:

Frown (Error)

Error Message:
Value cannot be null.
Parameter name: modelingRelationship

Thanks


Status:
New


See more ideas labeled with:

  • Reports


  • Back to Idea Exchange

Comments

    • 1
    • 2
  • Next

Same.  Updated an hour ago and now getting this error

@Anonymous,

Which specific step do you take when you get the above error, import data from your source to Power BI Desktop or apply query changes?

Are you able to take same operation in old version of Power BI Desktop? Could you please share the steps you take and source file so that I can test?

Regards,
Lydia

Hello,

I try to refresh the data from my data source, then I get a window ‘ queries changes are applying’, then I get this error. In the old version everything was working. I think you won’t be able to test it cause I am connecting to our SQL server. Thanks for any advice in advance.

KR,

T.

Same. Connecting to SQL server.  «Applying» causes this error…on newly created reports and already created reports.

…And the old one remains :((( Does anyone have any news regarding the issue?

I rolled back to the previous version of PBI.  No more error. Although, not a solution, it’s the only thing that worked.

Hello. I’m getting the same errors, but I think is when PBI is going to create relationships.

Turn off «Autodetect new relationship after data is loaded» and work.

@Anonymous,

Could you please share the T-SQL you use to create the SQL tables so that I can replicate?

Regards,
Lydia

    • 1
    • 2
  • Next


  • Back to Idea Exchange

You must be a registered user to add a comment. If you’ve already registered, sign in. Otherwise, register and sign in.

  • Comment

  • Ошибка valorant directx runtime
  • Ошибка val 9 валоран
  • Ошибка val 51 валорант что делать
  • Ошибка val 51 валорант при запуске
  • Ошибка vac не смогла определить вашу игровую сессию