2011-01-21 30 views
1

我試圖從ButtonField(數據綁定)訪問文本,但如果我將它作爲TableCell引用,則無法獲取文本。我能做些什麼來獲得它的文本?如何訪問ButtonFields文本,如果它不被視爲TableCell?

標記:

<asp:GridView ID="gvClass" runat="server" CssClass="grid" HeaderStyle-Font-Bold="true" Width="100%" OnSelectedIndexChanged="gvClass_SelectedIndexChanged" DataKeyNames="ClassID" AutoGenerateColumns="False" OnPageIndexChanging="gvClass_PageIndexChanging"> 
    <HeaderStyle Font-Bold="True" /> 
    <Columns> 
     <asp:ButtonField DataTextField="ClassID" HeaderText="Class ID" CommandName="Select" /> 
     <asp:BoundField DataField="CourseName" HeaderText="Course Name" /> 
     <asp:BoundField DataField="WarehouseName" DataFormatString="Warehouse" HeaderText="Warehouse" /> 
     <asp:BoundField DataField="TrainerNames" HeaderText="Trainer(s)" /> 
     <asp:BoundField DataField="StartTime" HeaderText="Start Time" /> 
     <asp:BoundField DataField="Duration" HeaderText="Duration" /> 
     <asp:BoundField DataField="Course Category" HeaderText="Course Category" /> 
     <asp:BoundField DataField="Comment" HeaderText="Comment" /> 
    </Columns> 
    <EmptyDataTemplate> 
     <span class="italic grey">No Record Found</span> 
    </EmptyDataTemplate> 
</asp:GridView> 

代碼隱藏:

foreach (GridViewRow gvr in gvClass.Rows) 
{ 
    foreach (TableCell tc in gvr.Cells) 
    { 
     stringToAppend = tc.Text; 
     sb.Append(PRTL_UtilityPackage.FormatHtmlCharacters(stringToAppend) + " \t"); 
    } 
    sb.Append("\\n"); 
} 

在foreach(TableCell的TC在gvr.Cells)看ButtonField字段時爲空字符串出現。

回答

8

,您仍然可以使用TableCell的方法:

protected void myGridView_DataBound(object sender, GridViewRowEventArgs e) 
{ 
    if (e.Row.RowType == DataControlRowType.DataRow) 
    { 
     // You may have to play with the index of the control 
     // I have found that often a GridView will place a 
     // Literal control as Control[0] and the LinkButton 
     // as Control[1]. Once you find the index, it won't 
     // change. 
     LinkButton btn = (LinkButton)e.Row.Cells[0].Controls[1]; 
     string text = btn.Text; 
    } 
} 
+0

適合我的最佳方法 – wubblyjuggly 2015-12-30 16:50:06

0

在ButtonField字段,還有的小區內的另一個控件,你需要獲得的文本:

Control control = gvr.Cells[0].Controls[0]; 
string text = string.Empty; 
if (((ButtonField)gvClass.Columns[0]).ButtonType == 
    ButtonType.Link) 
{ 
    LinkButton btn = control as LinkButton; 
    text = btn.Text; 
} 
else 
{ 
    Button btn = control as Button; 
    text = btn.Text; 
} 
+0

什麼是`gvr`?那是GridView的名字? – Si8 2014-06-11 16:15:39

1
Dim lbtn As Button = DirectCast(gwvFileList.Rows(e.CommandArgument).Cells(1).Controls(0), Button) 
Dim sName As String = lbtn.Text 

例子: http://www.editingmate.com

相關問題