How to get the Membernames property with the index?

Asked

Viewed 34 times

-4

I started programming in C# a little while ago and I’m doing a validation treatment using Data Annotation with windows Forms, I have a problem that I can’t get the Membernames property from the Ienumerable Interface by index, how can I get the property of index 0, that is, the property Name.

inserir a descrição da imagem aqui

  • 1

    Include the code in the question and not just a screenshot of your IDE

1 answer

0


Since MemberNames is a string[] and you want to retrieve the first value from it you can explicitly use index 0, provided that you check whether in fact the array has been initialized. Another option is the method FirstOrDefault(), adding the reference of System.Linq.

var _obj = "";
var memberNames = error.MemberNames;

//Pelo índice
_obj = (memberNames != null) ? memberNames[0] : "";

//Usando Linq
_obj = memberNames?.FirstOrDefault() ?? "";

After you edit your question, with your code is the class that is validating, I edit the question with a more complete answer.

  • thanks for the answer. I come from VB and I started to do some things in C#, so I curl up sometimes. Your example worked perfectly with the Link, with the index not working, but already worked the way I wanted. I’ll attach the example code, which is very simple, just so you know. I will perfect a better error handling, because I am using the validations of Data Annotation to implement in the system of the company I started working and has a very large system, which gives several errors because of the character size of the fields that are not treated

  • are not treated in forms, as there are many fields and little time, I will use the validations mapping the classes themselves. Project link

  • The first option was not working because I had misspelled a variable, it is fixed now. If the answer solved your problem mark your question as answered.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.