skinid net example editar editable bootstrap asp asp.net gridview

example - gridview asp.net vb



gridview muestra el texto en lugar de los valores (3)

mi pregunta es:

mi tabla consta de estos valores: 0, 1, 2 3

pero cuando se carga la vista de cuadrícula, quiero que se muestre el texto en lugar de solo esos números.

0 = not set, 1 = low, 2 = medium, 3 = high

Podría haber hecho esto como condición if / else, pero solo quería buscar un sol optimizado.

aquí está mi gridview markup:

<asp:TemplateField HeaderText="Priority" SortExpression="Priority" > <ItemTemplate> <asp:Label ID="lblPriority" Text=''<%# DataBinder.Eval(Container.DataItem,"Priority")%>'' runat="server" /> </ItemTemplate>


¿Por qué no usar enumeraciones? Aquí:

Tener una enumeración llamada Prioridad. A continuación, coloque el atributo Description en cada uno de ellos y escriba el texto de visualización dentro del constructor de ese atributo.

public enum Priority { [Description("not set")] NotSet = 0, [Description("low")] Low = 1, [Description("medium")] Medium = 2, [Description("high")] High = 3 }

A continuación, utilice el método Enum.ToObject para convertir los números (valores) en su valor de visualización asociado utilizando estas funciones:

// An extension method for ease of use that converts an integer into enum public static T ToEnum<T>(this int value) { if (typeof(T).BaseType.Name != typeof(Enum).Name) { throw new Exception("Input type of generic method ToEnum<T>() is not an Enum"); } return (T)Enum.ToObject(typeof(T), value); } // Another extension method that gets the display text of the Description attribute of a given enum constant public static string GetDescription(this Enum value) { return ((DescriptionAttribute)value.GetType().GetField(value.ToString()).GetCustomAttributes(typeof(DescriptionAttribute), false)[0]).Description; }

Luego, en tu código, puedes escribir:

databaseValue.ToEnum<Priority>().GetDescription();


Suponiendo que no tiene los valores de visualización almacenados en el DB en ninguna parte, esta es una forma de implementar la parte de representación. Puede haber una manera más fácil de mantener los valores de búsqueda, si alguien pudiera contribuir, lo agradecería.

Escribí esto en el bloc de notas porque no tengo Visual Studio en mi máquina. Disculpe si hay algún error de sintaxis.

Margen:

<asp:Label ID="lblPriority" Text=''<%# RenderPriority(DataBinder.Eval(Container.DataItem,"Priority")) %>'' runat="server" />

Código:

Protected Function RenderPriority(ByVal dbValue As Object) As String Dim strReturn as String = String.Empty If Not IsDbNull(dbValue) Then Dim intValue as Integer If Integer.TryParse(dbValue, intValue) Then Select Case intValue Case 0 strReturn = "not set" Case 1 strReturn = "low" Case 2 strReturn = "medium" Case 3 strReturn = "high" End Select Else strReturn = dbValue.ToString() End If End If Return strReturn End Function

Editar:

Después de volver a leer su pregunta, me da la impresión de que preferiría evitar escribir una función específica para este propósito en la página de código subyacente. Si ese es el caso, probablemente debería almacenar las cadenas que desea asociar con los valores de clave en el DB y sacarlos a través de su instrucción SQL. O, al menos, inserte la funcionalidad en una capa de acceso a datos. De cualquier manera, idealmente, la columna GridView se presentará con la cadena requerida por su fuente de datos.


Puede usar el evento RowDataBound de GridView y establecer el valor en condiciones específicas.

Aquí está el código completo ...

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e) { if (e.Row.RowType == DataControlRowType.DataRow) { System.Data.DataRow dr = ((System.Data.DataRowView)e.Row.DataItem).Row; if (dr["Priority"].ToString() == "0") { ((Label)e.Row.FindControl("lblPriority")).Text = "not set"; } else if (dr["Priority"].ToString() == "1") { ((Label)e.Row.FindControl("lblPriority")).Text = "low"; } else if (dr["Priority"].ToString() == "2") { ((Label)e.Row.FindControl("lblPriority")).Text = "medium"; } else if (dr["Priority"].ToString() == "3") { ((Label)e.Row.FindControl("lblPriority")).Text = "high"; } } }