最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

c# - How to optionally display buttons in GridView if Eval is not null? - Stack Overflow

programmeradmin1浏览0评论

I have the following GridView and ObjectDataSource:

<asp:GridView 
    ID="grdTrades" 
    runat="server" 

    DataSourceID="srcTrades" 
    DataKeyNames="tradeId"
    EnablePersistedSelection="true"            
    SelectedRowStyle-BackColor="Yellow" 
    AllowPaging="true" 
    AllowSorting="true"
    PageSize = "10" 
    AutoGenerateColumns="false" 
    >
    <Columns>
        <asp:CommandField ShowSelectButton="true" ButtonType="Link" SelectText="Select" />                           
        <asp:BoundField DataField="tradeId" HeaderText="TradeId"  ReadOnly="True" SortExpression="tradeId" />
        <asp:BoundField DataField="symbol" HeaderText="Pair" SortExpression="symbol" />
        <asp:BoundField DataField="chartTimeFrame" HeaderText="TF" SortExpression="chartTimeFrame" />
        <asp:BoundField DataField="tradeSetupId" HeaderText="Setup" SortExpression="tradeSetupId" />
        <asp:BoundField DataField="tradeType" HeaderText="Trade Type" SortExpression="tradeType" />
        <asp:BoundField DataField="side" HeaderText="Side"  ReadOnly="True" SortExpression="side" />
        <asp:BoundField DataField="units" HeaderText="Units"  ReadOnly="True" SortExpression="units" />
        <asp:BoundField DataField="price" HeaderText="Price" SortExpression="price" />
        <asp:BoundField DataField="orderDateTime" HeaderText="Order Date/Time" SortExpression="orderDateTime" />
        <asp:BoundField DataField="pipsProfit" HeaderText="Pips profit" DataFormatString="{0:F1}" SortExpression="pipsProfit" />
        <asp:BoundField DataField="riskPips" HeaderText="Pips risked" DataFormatString="{0:F1}" SortExpression="riskPips" />
        <asp:BoundField DataField="pipsInMove" HeaderText="Pips in move" DataFormatString="{0:F1}" SortExpression="pipsInMove" />
        <asp:BoundField DataField="rewardRiskRatio" HeaderText="R/R" DataFormatString="{0:F1}" SortExpression="rewardRiskRatio" />            
        <asp:BoundField DataField="pctAccountRisked" HeaderText="% risk" DataFormatString="{0:F1}" ReadOnly="True" SortExpression="pctAccountRisked" />
        <asp:BoundField DataField="pctAccountChange" HeaderText="% AcctChange" DataFormatString="{0:F2}" SortExpression="pctAccountChange" />            
        <asp:TemplateField>
            <ItemTemplate>
                <input type="button" size="x-small" value="View" onclick="javascript:ShowImageInNewPage('DisplayImage.aspx?screenshotId=<%# Eval("screenshotId") %>');" />
            </ItemTemplate>
        </asp:TemplateField>
        <asp:HyperLinkField 
            Text="Edit"
            DataNavigateUrlFields="tradeId" 
            DataNavigateUrlFormatString="EditTrade.aspx?screenshotId={0}" />                
        <CustomControls:DeleteButtonField ConfirmText="Delete this trade?" Text="Del" />
    </Columns>
</asp:GridView>

<CustomControls:CustomObjectDataSource
    id="srcTrades" 
    TypeName="DatabaseComponent.DBUtil" 
    SelectMethod="GetTrades" 
    DeleteMethod="DeleteTrade"             
    runat="server">
    <DeleteParameters>
        <asp:ControlParameter Name="tradeId" ControlId="grdTrades" PropertyName="SelectedValue"  />
    </DeleteParameters> 
</CustomControls:CustomObjectDataSource>  

In my TemplateField I only want to display the button if screenshotId evaluates to a non-null non-zero value. If screenshotId is DbNull or 0 then I want to leave the cell blank. Where should I code this, in the ASP.NET code or do I have to write some code-behind? What's the best way?

UPDATE

I've added the following code:

protected void grdTrades_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        var dataitem = DataBinder.Eval(e.Row.DataItem, "screenshotId");
        Button btnShowImage = e.Row.FindControl("btnShowImage") as Button;
        if (dataItem.screenshotId != null && screenshotId > 0)
        {
            btnShowImage.OnClientClick = "javascript:ShowImageInNewPage(\"DisplayImage.aspx?screenshotId=" + dataItem.screenshotId + "\");";
            btnShowImage.Visible = true;
        }
        else
            btnShowImage.Visible = false;                
    }
}  

However I get these errors:

The name 'dataItem' does not exist in the current context

and

The name 'screenshotId' does not exist in the current context

MyRow was not recogised either. Any ideas?

UPDATE 2

I finally worked it out - here's my code:

protected void grdTrades_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        // If you do it like this, you already get the screenshotId value;
        var screenshotId = DataBinder.Eval(e.Row.DataItem, "screenshotId");
        Response.Write("ScreenshotId: " + screenshotId.ToString());

        Button btnShowImage = e.Row.FindControl("btnShowImage") as Button;

        if (screenshotId is System.DBNull)
            btnShowImage.Visible = false;
        else            
        {
            btnShowImage.Text = screenshotId.ToString();
            btnShowImage.OnClientClick =
               "javascript:ShowImageInNewPage(\"DisplayImage.aspx?screenshotId=" + screenshotId.ToString() + "\");";
            btnShowImage.Visible = true;
        }            
    }
}

I have the following GridView and ObjectDataSource:

<asp:GridView 
    ID="grdTrades" 
    runat="server" 

    DataSourceID="srcTrades" 
    DataKeyNames="tradeId"
    EnablePersistedSelection="true"            
    SelectedRowStyle-BackColor="Yellow" 
    AllowPaging="true" 
    AllowSorting="true"
    PageSize = "10" 
    AutoGenerateColumns="false" 
    >
    <Columns>
        <asp:CommandField ShowSelectButton="true" ButtonType="Link" SelectText="Select" />                           
        <asp:BoundField DataField="tradeId" HeaderText="TradeId"  ReadOnly="True" SortExpression="tradeId" />
        <asp:BoundField DataField="symbol" HeaderText="Pair" SortExpression="symbol" />
        <asp:BoundField DataField="chartTimeFrame" HeaderText="TF" SortExpression="chartTimeFrame" />
        <asp:BoundField DataField="tradeSetupId" HeaderText="Setup" SortExpression="tradeSetupId" />
        <asp:BoundField DataField="tradeType" HeaderText="Trade Type" SortExpression="tradeType" />
        <asp:BoundField DataField="side" HeaderText="Side"  ReadOnly="True" SortExpression="side" />
        <asp:BoundField DataField="units" HeaderText="Units"  ReadOnly="True" SortExpression="units" />
        <asp:BoundField DataField="price" HeaderText="Price" SortExpression="price" />
        <asp:BoundField DataField="orderDateTime" HeaderText="Order Date/Time" SortExpression="orderDateTime" />
        <asp:BoundField DataField="pipsProfit" HeaderText="Pips profit" DataFormatString="{0:F1}" SortExpression="pipsProfit" />
        <asp:BoundField DataField="riskPips" HeaderText="Pips risked" DataFormatString="{0:F1}" SortExpression="riskPips" />
        <asp:BoundField DataField="pipsInMove" HeaderText="Pips in move" DataFormatString="{0:F1}" SortExpression="pipsInMove" />
        <asp:BoundField DataField="rewardRiskRatio" HeaderText="R/R" DataFormatString="{0:F1}" SortExpression="rewardRiskRatio" />            
        <asp:BoundField DataField="pctAccountRisked" HeaderText="% risk" DataFormatString="{0:F1}" ReadOnly="True" SortExpression="pctAccountRisked" />
        <asp:BoundField DataField="pctAccountChange" HeaderText="% AcctChange" DataFormatString="{0:F2}" SortExpression="pctAccountChange" />            
        <asp:TemplateField>
            <ItemTemplate>
                <input type="button" size="x-small" value="View" onclick="javascript:ShowImageInNewPage('DisplayImage.aspx?screenshotId=<%# Eval("screenshotId") %>');" />
            </ItemTemplate>
        </asp:TemplateField>
        <asp:HyperLinkField 
            Text="Edit"
            DataNavigateUrlFields="tradeId" 
            DataNavigateUrlFormatString="EditTrade.aspx?screenshotId={0}" />                
        <CustomControls:DeleteButtonField ConfirmText="Delete this trade?" Text="Del" />
    </Columns>
</asp:GridView>

<CustomControls:CustomObjectDataSource
    id="srcTrades" 
    TypeName="DatabaseComponent.DBUtil" 
    SelectMethod="GetTrades" 
    DeleteMethod="DeleteTrade"             
    runat="server">
    <DeleteParameters>
        <asp:ControlParameter Name="tradeId" ControlId="grdTrades" PropertyName="SelectedValue"  />
    </DeleteParameters> 
</CustomControls:CustomObjectDataSource>  

In my TemplateField I only want to display the button if screenshotId evaluates to a non-null non-zero value. If screenshotId is DbNull or 0 then I want to leave the cell blank. Where should I code this, in the ASP.NET code or do I have to write some code-behind? What's the best way?

UPDATE

I've added the following code:

protected void grdTrades_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        var dataitem = DataBinder.Eval(e.Row.DataItem, "screenshotId");
        Button btnShowImage = e.Row.FindControl("btnShowImage") as Button;
        if (dataItem.screenshotId != null && screenshotId > 0)
        {
            btnShowImage.OnClientClick = "javascript:ShowImageInNewPage(\"DisplayImage.aspx?screenshotId=" + dataItem.screenshotId + "\");";
            btnShowImage.Visible = true;
        }
        else
            btnShowImage.Visible = false;                
    }
}  

However I get these errors:

The name 'dataItem' does not exist in the current context

and

The name 'screenshotId' does not exist in the current context

MyRow was not recogised either. Any ideas?

UPDATE 2

I finally worked it out - here's my code:

protected void grdTrades_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        // If you do it like this, you already get the screenshotId value;
        var screenshotId = DataBinder.Eval(e.Row.DataItem, "screenshotId");
        Response.Write("ScreenshotId: " + screenshotId.ToString());

        Button btnShowImage = e.Row.FindControl("btnShowImage") as Button;

        if (screenshotId is System.DBNull)
            btnShowImage.Visible = false;
        else            
        {
            btnShowImage.Text = screenshotId.ToString();
            btnShowImage.OnClientClick =
               "javascript:ShowImageInNewPage(\"DisplayImage.aspx?screenshotId=" + screenshotId.ToString() + "\");";
            btnShowImage.Visible = true;
        }            
    }
}
Share Improve this question edited Nov 11, 2010 at 9:12 Mark Allison asked Nov 9, 2010 at 10:07 Mark AllisonMark Allison 7,23835 gold badges106 silver badges158 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 2

Could you do it all declaratively?

    <asp:TemplateField>
        <ItemTemplate>
                <input runat="server" visible='<%# Eval("screenshotId") != DBNull.Value %>' type="button" size="x-small" value="View" onclick='<%# "ShowImageInNewPage(\"DisplayImage.aspx?screenshotId=" + Eval("screenshotId") + "\")" %>' />
        </ItemTemplate>
    </asp:TemplateField>

the best way is to handle OnRowDataBound event.

<ItemTemplate>
   <asp:Button runat="server" ID="btnShowImage" />                
</ItemTemplate>

Then in your code behind:

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if(e.Row.RowType == DataControlRowType.DataRow)
    {
        // If you do it like this, you already get the screenshotId value;
        var screenshotId = DataBinder.Eval(e.Row.DataItem, "screenshotId");

        Button btnShowImage = e.Row.FindControl("btnShowImage") as Button;

        if(screenshotId != null && screenshotId > 0)
        {
            btnShowImage.OnClientClick = 
               "javascript:ShowImageInNewPage(\"DisplayImage.aspx?screenshotId=" +  screenshotId.ToString() + "\");";
            btnShowImage.Visible = true;
        }
        else
            btnShowImage.Visible = false;
    }
}

Something like that, but you'll have to improve it according to your needs. Don't forget to add the event handler to your GridView markup as well.

<asp:GridView OnRowDataBound="GridView1_RowDataBound".... />
发布评论

评论列表(0)

  1. 暂无评论