Programmatically Access and Manage GridView Columns

I have a gridview:

<asp:GridView ID="GridView1" runat="server" AllowPaging="True" GridLines="None" 
                HorizontalAlign="Left" AutoGenerateColumns="False" 
                DataSourceID="SqlDataSource1" onrowcommand="GridView1_RowCommand1">            
                <HeaderStyle HorizontalAlign="Left" />                            
                <Columns>  
                   <asp:TemplateField HeaderStyle-Width="150">
                        <HeaderTemplate>
                            <b>Downloads</b>
                        </HeaderTemplate>
                        <ItemTemplate>
                            <!-- <asp:HyperLink ID="hyperlinkDownload" runat="server" NavigateUrl="" >Download 
                            MP3</asp:HyperLink> -->
                            <asp:LinkButton CommandName="download"
                             CommandArgument='<%# Eval("Name") %>' runat="server">Download MP3</asp:LinkButton>
                        </ItemTemplate>
                    </asp:TemplateField>    

</asp:GridView>

I want to request the value of a specific field in the database, and if it is true, display LinkButton. if false, I want linkButton not to display.

Is there a way to access the GridView programmatically and make some of its columns visible or manipulate its elements?

help.

+1
source share
2 answers

You can do this by adding an event handler RowDataBound. Add an event handler for these lines of this code:

protected void myGrid_RowDataBound(Object sender, GridViewRowEventArgs e)
{
    var data = e.Row.DataItem as DataRowView;
    if (data != null)
    {
        var lbtDownload = e.Row.FindControl("lbtDownload");
        lbtDownload.Visible = (bool) data.Row["HasFileForDownload"];
    }
}

In your markup, attach an event handler to the grid:

<asp:GridView OnRowDataBound="myGrid_RowDataBound" ...>

id LinkButton, , , FindControl() .

: Linux- - . , - , .

+2

, .

1) RowDataBound.
2) LinkButton ID.
3) codebehind

  protected void GridView1_RowDataBound(Object sender, GridViewRowEventArgs e)
  {
    if(e.Row.RowType == DataControlRowType.DataRow)
    { 
      LinkButton _bt = e.Row.FindControl("ID") as LinkButton;
      if(_bt != null)
      {
        // have a look at the e.row.DataItem and try to get the value of your desired visibility property
        _bt.Visible = true;
      }
    }
  }

4) DataItem, LinqDataSource.

+2

Source: https://habr.com/ru/post/1767008/


All Articles