Error converting an Enum

Asked

Viewed 39 times

0

Good evening guys, I’m new in C# and would like if possible a help, I created an Enum with client codes and I’m trying to pass its value through a validation and I’m getting string to int conversion error,

"Conversion failed when Converting the varchar value 'Client' to data type int."

I believe my Enum is already int and I do not know why I get the error, follow below:

My Enum:

public class Cliente
{
    public Clientes ClienteId { get; set; }
    
}

public enum Clientes : int
{
    Cliente = 1,
    Cliente2 = 2
}

at Index I get him like this:

@Html.EnumDropDownListFor(model => model.Cliente,"--Escolha o cliente--")

The query :

public DataTable ConsultarPedido(string pedidoid,Clientes cliente)
{
    try
    {
        var consultar = $@"SELECT p.pedidoid, p.clienteid, p.statuspedido FROM dbo.Pedido p JOIN dbo.ItemPedido ip ON p.PedidoId = ip.PedidoId WHERE  p.PedidoId ='{pedidoid}' AND p.ClienteId='{cliente}'";

        return new AcessoBanco().RunQuery(consultar).Tables[0];
    }

1 answer

0

If I understand correctly, its enumerated value is receiving an implicit conversion to string, given that it is in a string interpolation and your column accepts only values int.

That means at your value cliente the method ToString() is being called at runtime to enable formatting of the string end (which, in your case, is the query). Try to convert it to int when passing the value, either by converting with the convert class or by casting:

Convert.ToInt32(cliente) or (int)cliente.

The final result should reflect on "1", for example and not "Cliente" as occurs in the conversion of enum for string.

I hope I’ve helped in some way.

  • Ruan thanks so much for the help, in my controller I did this:public Actionresult Index(Request items) atin atin var pedido = new Pedido(); Viewdata["Pedidoid"] = pedido.Pedidoid; Viewdata["Client"] = (int)pedidos.Cliente; I don’t know where to make the conversion.

  • Try to make the conversion during the assembly of your query (in the interpolation {cliente}). The interpolation I mentioned will call the method ToString() in what is available, aiming to format the string correctly. The error you are receiving calls your string of varchar, then most likely it is coming from the API connection to your database, ie during the execution of the converted query.

  • Okay got it, thank you very much Ruan I’ll adjust.

Browser other questions tagged

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