Доступ к данным GridView из поля шаблона - PullRequest
2 голосов
/ 04 августа 2011
    <asp:GridView ID="gvGrid" runat="server" AutoGenerateColumns="False" 
        DataSourceID="dsDataSource" AllowPaging="True" PageSize="20" >
        <Columns>
            <asp:BoundField DataField="Field1" HeaderText="Field1" 
                SortExpression="Field1" />
            <asp:BoundField DataField="Field2" HeaderText="Field2" 
                SortExpression="Field2" />
            <asp:TemplateField HeaderText="TemplateField1">
                <ItemTemplate>
                    <asp:Label id="lblComments" runat="server" Text=" i use a function to compute"></asp:Label>
                </ItemTemplate> 
            </asp:TemplateField>

          <asp:CommandField ShowSelectButton="True" SelectText="Complete" HeaderText ="Status" />

            <asp:TemplateField HeaderText="Action">
                <ItemTemplate>
                       <asp:Button ID="btnComplete" runat="server" Text="Complete" onclick="btnComplete_Click"/>
                    <asp:Button ID="btnAddComment" runat="server" Text="Add Comment" onclick="btnAddComment_Click" />    
                </ItemTemplate>
            </asp:TemplateField>
        </Columns>
    </asp:GridView>

protected void btnComplete_Click(object sender, EventArgs e) 
{

    String Field1 = gvGrid.SelectedRow.Cells[1].Text; // throws an error at runtime

   //I want to be able to access the row data do some computation and then be able to insert it into the database 
// Reason why I am trying to use it as a template field instead of a commandfield is because I want to make it not visible when it meets certain condition. 
}

Также было бы здорово, если бы вы могли сообщить мне лучший способ сделать это, возможно, с помощью поля команды и если есть способ переключить его видимость.Я тоже не против использования LinkButton.

Ответы [ 2 ]

3 голосов
/ 04 августа 2011

Вы можете сделать это так:

protected void btnComplete_Click(object sender, EventArgs e)    
{  
     Button btn = (Button)sender;
     GridViewRow gvRow = (GridViewRow)btn.Parent.Parent;

     //Alternatively you could use NamingContainer
     //GridViewRow gvRow = (GridViewRow)btn.NamingContainer;

     Label lblComments = (Label)gvRow.FindControl("lblComments");

     // lblComments.Text ...whatever you wanted to do
}
1 голос
/ 04 августа 2011

вот как вы можете получить доступ к строке сетки:

protected void btnComplete_Click(object sender, EventArgs e)    
{  
     foreach (GridViewRow row in gvGrid.Rows)
      {
            Label lblComments = row.FindControl("lblComments") as Label;
            ....//you can do rest of the templatefiled....
      }
}
...