如何处理Null(GridView Container.DataItem)

时间:2011-01-19 01:59:29

标签: asp.net gridview

这里有什么不对,为什么抱怨关闭")"

<asp:TemplateField HeaderText="Name" SortExpression="Name">
                    <ItemTemplate>   
                        <%# FixNull((namespace.Student)(Container.DataItem), "Name"); %>               
                    </ItemTemplate>
                    <EditItemTemplate>
                       <asp:dropdownlist id="ddlStudent" runat="server" datasourceid="CountyDataSource"
                            datatextfield="Name" datavaluefield="Id" autopostback="false">
                        </asp:dropdownlist>
                    </EditItemTemplate>
                </asp:TemplateField>

 protected string FixNull(object dataItem, string fieldName)
 {
        if (dataItem != null)
        {
            System.Data.DataRowView cls = (System.Data.DataRowView)dataItem;
            if (!cls.Row.IsNull(fieldName))
                return (cls[fieldName]).ToString();
            else
                return "&nbsp;";
        }
        else
            return "&nbsp;";
    }



Compiler Error Message: CS1026: ) expected

Source Error: Line: 133 


Line 131:                  <asp:TemplateField HeaderText="Name" SortExpression="Name">
Line 132:                    <ItemTemplate>   
Line 133:    <%# FixNull((namespace.Student)(Container.DataItem), "Name"); %>               
Line 134:                    </ItemTemplate>
Line 135:                    <EditItemTemplate>

4 个答案:

答案 0 :(得分:5)

<%# Eval("CountyName") == null ? "&nbsp;" : Eval("CountyName")%>   

答案 1 :(得分:1)

我认为,您不需要;

它应该只读:

<%# FixNull((namespace.Student)(Container.DataItem), "Name") %>

答案 2 :(得分:1)

为了进一步简化,您可以使用

<%# this.Eval("CountyName") ?? "&nbsp;"%>

答案 3 :(得分:0)

也许尝试这样的事情:

 <asp:TemplateField HeaderText="Name" SortExpression="Name">
    <ItemTemplate>   
        <%# FixNull(DataBinder.Eval(Container.DataItem, "Name"))%>               
    </ItemTemplate>
    <EditItemTemplate>
        <asp:dropdownlist id="ddlStudent" runat="server" datasourceid="CountyDataSource"
            datatextfield="Name" datavaluefield="Id" autopostback="false">
        </asp:dropdownlist>
    </EditItemTemplate>
</asp:TemplateField>


protected string FixNull(string dataItem)
{
    if (!string.IsNullOrEmpty(dataItem))
    {
        return dataItem;
    }
    return "&nbsp;";
}