【问题标题】:Getting the default value of Label in the Gridview if the one of the column value is null如果列值之一为空,则在 Gridview 中获取 Label 的默认值
【发布时间】:2019-03-15 01:56:42
【问题描述】:

下面是我的网格视图

 <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" EnableModelValidation="True" onrowdatabound="GridView1_RowDataBound" onrowcommand="GridView1_RowCommand" onrowdeleting="GridView1_RowDeleting"> 
  <asp:TemplateField HeaderText="Amount" HeaderStyle-ForeColor="DimGray" >
<ItemTemplate>
<asp:Label ID="lblamount" runat="server" Text='Label' ></asp:Label>
</ItemTemplate>
</asp:TemplateField>

<asp:TemplateField HeaderText="Price" HeaderStyle-ForeColor="DimGray" >
<ItemTemplate>
<asp:Label ID="lblprice" runat="server" Text='Label' ></asp:Label>
</ItemTemplate>
</asp:TemplateField>

在 RowData_BoundEvent 中

  protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
     if (e.Row.RowType == DataControlRowType.DataRow)
        {
     Label lbl2 = (Label)e.Row.FindControl("lblamount");
      if(amount>0) {lbl2.Text = amount;} else lbl2.Text = string.Empty;

      Label lbl3 = (Label)e.Row.FindControl("lblprice");
            if(price>0) {lbl3.Text = price;} else lbl3.Text = string.Empty;

如果在 Amount 或 Price 中没有输入值,如果金额不大于零,我会尽量不在 gridview 中显示值。但是,如果条件不满足,网格仍将金额显示为标签,价格显示为标签。

【问题讨论】:

    标签: asp.net


    【解决方案1】:

    您应该使用GridViewRow's DataItem 来获取这些值。

    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
          // Retrieve the underlying data item. In this example
          // the underlying data item is a DataRowView object. 
          DataRowView rowView = (DataRowView)e.Row.DataItem;
    
          Double amount = (Double)(rowView["amount"]);
          Double price =  (Double)(rowView["price"]);
    
          Label lblamount= (Label)e.Row.FindControl("lblamount");
          Label lblprice = (Label)e.Row.FindControl("lblprice");
    
          lblamount.Text = amount > 0 ? amount.ToString() : String.Empty;
          lblprice.Text  = price  > 0 ? price.ToString()  : String.Empty;
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2018-03-06
      • 2012-12-01
      • 2021-10-16
      • 2023-03-03
      • 2016-01-02
      • 2015-02-13
      • 2019-03-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多