I read data from an entity framework and bind a repeater on an ASP.NET page (ASPX) to it. One of my fields - iFieldType
- contains an integer value which is parsed to an item of an enumeration in the markup of the page like that:
<owiw:CustomTextBox runat="server" ReadOnly="true" ID="txt_FieldType"
Text='<%# Enum.Parse(typeof(DatabaseHelper.CustomFieldTypes), Convert.ToString(DataBinder.Eval(Container.DataItem, "iFieldType"))) %>' />
That's because the users don't want to see per example "1" on the page, but the name of the fieldtype "TextBox". Unfortunately iFieldType
can be NULL
. So i have to replace Enum.Parse
by Enum.TryParse
. Can this be done in the markup/html?
There are at least two possible solutions.
A) We can program in code-behind of the page a public(!) method which does the tryparse.
Per example:
public string FieldTypeTryParseToString(object value)
{
if (value == null)
{
return "0";
}
return value.ToString();
}
Then in the markup we implement the new method:
<owiw:CustomTextBox runat="server" ReadOnly="true" ID="txt_FieldType"
Text='<%# Enum.Parse(typeof(DatabaseHelper.CustomFieldTypes), FieldTypeTryParseToString(DataBinder.Eval(Container.DataItem, "iFieldType"))) %>' />
B) We can do it in the markup too but it will make the code more complex. In this case we check if the value is null.
<owiw:CustomTextBox runat="server" ReadOnly="true" ID="txt_FieldType"
Text='<%# Enum.Parse(typeof(DatabaseHelper.CustomFieldTypes), DataBinder.Eval(Container.DataItem, "iFieldType") == null ? "0" : Convert.ToString(DataBinder.Eval(Container.DataItem, "iFieldType"))) %>' />
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.