简体   繁体   English

如何解决 Value 不能为 null。 参数名称:linq 中的源?

[英]How to resolve Value cannot be null. Parameter name: source in linq?

I don't know why I get this kind of error.我不知道为什么会出现这种错误。 It happens sometimes, and I suspicious of my code that still have thread running while I close my Application.它有时会发生,我怀疑我的代码在关闭应用程序时仍然有线程在运行。 So when I open again it happens.所以当我再次打开时它发生了。

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:\handita\Office\Project\Susenas 2015\Aplikasi Template Survei\Susenas2015\ViewModels\Kuesioner\VMVsen15_KVal.cs:line 430
   at Susenas2015.ViewModels.Kuesioner.VMVsen15_KVal.vSen15_K_Loaded(Object sender, RoutedEventArgs e) in d:\handita\Office\Project\Susenas 2015\Aplikasi Template Survei\Susenas2015\ViewModels\Kuesioner\VMVsen15_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`

My code here it is我的代码在这里

    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");
            }

        }

When I start my application for my first time, it doesn't get any error.当我第一次启动我的应用程序时,它没有出现任何错误。 It happens when I open in 2nd or more.当我打开第二个或更多时会发生这种情况。 And if I open my application it would stuck in that code.如果我打开我的应用程序,它会卡在该代码中。

How I can solve this?我该如何解决这个问题? I'm pretty sure that my Property ListMetadataKor is not null我很确定我的 Property ListMetadataKor不为null

And ListMetadataKor is instance of List<Metadata> object that I have created. ListMetadataKor 是我创建的List<Metadata>对象的实例。 It happens only in rare cases.它只发生在极少数情况下。 And I don't know to solve it我不知道解决它

UPDATE更新

This is my code in image这是我在图像中的代码在此处输入图片说明

I fill ListMetadataKor with this code我用这个代码填充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);
    }
});

And then I throw the variable through constructor of my class然后我通过我的类的构造函数抛出变量

 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;

My tools konsistensi like this我的工具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;
}

Error message clearly says that source parameter is null .错误消息清楚地表明source参数为null Source is the enumerable you are enumerating. Source 是您正在枚举的枚举。 In your case it is ListMetadataKor object.在您的情况下,它是ListMetadataKor对象。 And its definitely null at the time you are filtering it second time.在您第二次过滤时它绝对为null Make sure you never assign null to this list.确保您永远不会为此列表分配null Just check all references to this list in your code and look for assignments.只需检查代码中对此列表的所有引用并查找分配。

Value cannot be null.值不能为空。 Parameter name: source参数名称:来源

Above error comes in situation when you are querying the collection which is null.当您查询为 null 的集合时,会出现上述错误。

For demonstration below code will result in such an exception.为了演示,下面的代码会导致这样的异常。

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

Here is the output of the above code.这是上面代码的输出。

Hello World Run-time exception (line 11): Value cannot be null. Hello World 运行时异常(第 11 行):值不能为空。 Parameter name: source参数名称:来源

Stack Trace:堆栈跟踪:

[System.ArgumentNullException: Value cannot be null. [System.ArgumentNullException:值不能为空。 Parameter name: source] at Program.Main(): line 11参数名称:source] 在 Program.Main():第 11 行

In your case ListMetadataKor is null.在您的情况下ListMetadataKor为空。 Here is the fiddle if you want to play around.如果你想玩,这里是小提琴。

When you call a Linq statement like this:当您像这样调用 Linq 语句时:

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

You are actually using an extension method in the System.Linq namespace, so what the compiler translates this into is:您实际上是在 System.Linq 命名空间中使用扩展方法,因此编译器将其转换为:

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

So the error you are getting above is because the first parameter, source (which would be x in the sample above) is null.因此,您遇到的错误是因为第一个参数source (在上面的示例中为x )为空。

System.ArgumentNullException: Value cannot be null. System.ArgumentNullException:值不能为空。 Parameter name: value参数名称:值

This error message is not very helpful!此错误消息不是很有帮助!

You can get this error in many different ways.您可以通过多种不同方式获得此错误。 The error may not always be with the parameter name: value .错误可能并不总是与参数名称: value 有关 It could be whatever parameter name is being passed into a function.它可以是传递给函数的任何参数名称。

As a generic way to solve this, look at the stack trace or call stack:作为解决此问题的通用方法,请查看堆栈跟踪或调用堆栈:

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)

You can see that the parameter name value is the first parameter for DeserializeObject .您可以看到参数名称valueDeserializeObject的第一个参数。 This lead me to check my AutoMapper mapping where we are deserializing a JSON string.这让我检查了我们反序列化 JSON 字符串的 AutoMapper 映射。 That string is null in my database.该字符串在我的数据库中为空。

You can change the code to check for null.您可以更改代码以检查是否为空。

Below mentioned error faced in crystal report export in excel format. 下面提到的问题以Excel格式导出到Crystal报表中。

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()

my problem was with spelling It was case sensitive!我的问题是拼写 区分大小写! Few of the columns were sorting properly and rest were throwing this error!很少有列正确排序,其余列抛出此错误!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 "<i>Value cannot be null.<\/i>值不能为空。<\/b> <i>Parameter name: source<\/i>参数名称:来源<\/b>" - Value cannot be null. Parameter name: source 使用LINQ在List中查找项目但获取“Value不能为null。 参数名称:source“ - Using LINQ to find item in a List but get “Value cannot be null. Parameter name: source” LINQ实体框架值不能为null。 参数名称:字符串 - LINQ Entity Framework Value cannot be null. Parameter name: String 值不能为空。 参数名称:Asp.net中的源 - Value cannot be null. Parameter name: source in Asp.net 值不能为空。 参数名称:测试模拟时的来源 - Value cannot be null. Parameter name: source at when test mock Azure 函数:值不能为空。 参数名称:来源 - Azure function: Value cannot be null. Parameter name: source Blazor + MongoDb 标识:值不能是 null。 (参数名称“来源”) - Blazor + MongoDb Identity: Value cannot be null. (Parameter name 'source') 如何修复“值不能为空。参数名称:值” - How to fix "Value cannot be null. Parameter name: value" 值不能为null。参数名称:String - Value cannot be null. Parameter name: String 值不能为空。 参数名称:路径 - Value cannot be null. Parameter name: path
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM