简体   繁体   English

试图让我陷入条件NULL语法

[英]Trying to get my head wrapped around Conditional NULL syntax

I've got a ASP.NET search page that displays a SQL bound ListView after a Search button is clicked. 我有一个ASP.NET搜索页面,该页面在单击“搜索”按钮后显示与SQL绑定的ListView。 In the EmptyDataTemplate, I've got an asp label based on the ID they searched for in a message. 在EmptyDataTemplate中,我有一个基于他们在消息中搜索的ID的asp标签。 "No results found for " kinda thing. “找不到结果”。

Here's my original codebehind for the button click: 这是单击按钮后的原始代码:

protected void btnSearch_Command(object sender, CommandEventArgs e)
{

    Label lbl = (Label)lvMatOrders.Controls[0].Controls[0].FindControl("lblProjectID");
    if (lbl != null)  // this means EmptyDataTemplate is used, else ItemTemplate
    {

        if (string.IsNullOrEmpty(txtProjectID.Text))
        {
            lbl.Text = "#####";
        }
        else
        {
            lbl.Text = txtProjectID.Text;
        }

    }
}

Am I correct in understanding that I can reduce it down to the following? 我是否可以将其简化为以下内容是否正确?

Label lbl = (Label)lvMatOrders.Controls[0].Controls[0].FindControl("lblProjectID");
lbl?.Text = (string.IsNullOrEmpty(txtProjectID.Text)) ? "#####" : txtProjectID.Text;

The main goal here is to make sure that the code that attempts to assign either the "#####" or txtProjectID.Text to lbl.Text doesn't get executed if the page already has results from a previous search displayed as the page isn't showing the EmptyDataTemplate and thus no lblProjectID to assign the text to. 此处的主要目标是确保如果页面已经具有先前搜索的结果显示为试图将试图将“ #####”或txtProjectID.Text分配给lbl.Text的代码,则不会执行。页面没有显示EmptyDataTemplate,因此没有分配文本的lblProjectID。

Will the lbl?.Text line be attempted if the page is in ItemTemplate mode? 如果页面处于ItemTemplate模式,是否会尝试lbl?.Text行?

No, the code will not even compile, you will get the error "The left-hand side of an assignment must be a variable, property or indexer" 不,代码甚至无法编译,您将收到错误“分配的左侧必须是变量,属性或索引器”

You can not use the .? 您不能使用.? operator on the left hand side of a equals sign, only the right hand side. 运算符位于等号的左侧,仅位于右侧。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM