前台程式碼
<asp:GridView ID="GridView1" runat="server"
Width="970px" BackColor="White" BorderColor="White" BorderStyle="Ridge"
BorderWidth="2px" CellPadding="3"
CellSpacing="1" GridLines="None" AutoGenerateColumns="False"
ShowHeaderWhenEmpty="True" EnableEventValidation="false" Visible="False"
EmptyDataText="查無資料,請用新增按鈕新增"
DataKeyNames="ID"
onselectedindexchanged="GridView1_SelectedIndexChanged" >
<Columns>
<asp:BoundField DataField="ID" HeaderText="ID" SortExpression="ID" />
<asp:BoundField DataField="病歷號" HeaderText="病歷號" SortExpression="病歷號" />
<asp:BoundField DataField="病患名稱" HeaderText="病患名稱" SortExpression="病患名稱" />
<asp:BoundField DataField="建檔日期" HeaderText="建檔日期" SortExpression="建檔日期" />
<asp:BoundField DataField="主治醫師" HeaderText="主治醫師" SortExpression="主治醫師" />
<asp:HyperLinkField NavigateUrl="Cancerplan-edit.aspx" Text="修改" />
<asp:CommandField ButtonType="Button" ShowSelectButton="True" />
</Columns>
<FooterStyle BackColor="#C6C3C6" ForeColor="Black" />
<HeaderStyle BackColor="#4A3C8C" Font-Bold="True" ForeColor="#E7E7FF" />
<PagerStyle BackColor="#C6C3C6" ForeColor="Black" HorizontalAlign="Right" />
<RowStyle BackColor="#DEDFDE" ForeColor="Black" />
<SelectedRowStyle BackColor="#9471DE" Font-Bold="True" ForeColor="White" />
<SortedAscendingCellStyle BackColor="#F1F1F1" />
<SortedAscendingHeaderStyle BackColor="#594B9C" />
<SortedDescendingCellStyle BackColor="#CAC9C9" />
<SortedDescendingHeaderStyle BackColor="#33276A" />
</asp:GridView>
後臺程式碼
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
Response.Write("gv selectedIndex: " + GridView1.SelectedIndex + "<br>");
Response.Write("gv selectedRow.RowIndex: " + GridView1.SelectedRow.RowIndex + "<br>");
Response.Write("gv selectedValue: " + GridView1.SelectedValue + "<br>");
Response.Write("gv SelectedDataKey.Value: " + GridView1.SelectedDataKey.Value + "<br>");
//<asp:CommandField ShowSelectButton="True" ButtonType="Button" /> 的捉法:
//Response.Write("gv 第八個欄位裡,按鈕的文字: " + ((Button)GridView1.Rows[GridView1.SelectedIndex].Cells[7].Controls[0]).Text + "<br>");
//<asp:TemplateField 裡手動塞 <asp:Button ID="Button1" runat="server" CausesValidation="False" CommandName="Select" Text="選取" /> 按鈕、捉 ID 的捉法:
Response.Write("gv 第1個欄位裡,按鈕的文字: " + ((Button)GridView1.Rows[GridView1.SelectedIndex].Cells[1].FindControl("Button")).Text + "<br>");
Response.Write("gv 第2個欄位裡,欄位裡的文字: " + GridView1.Rows[GridView1.SelectedIndex].Cells[2].Text + "<br>");
}
請問一下 我已經有給予DataKeyNames
為何在執行時 仍出現
System.InvalidOperationException: 必須先在 GridView 'GridView1' 上指定資料索引鍵,才能擷取選取的資料索引鍵。請使用 DataKeyNames 屬性指定資料索引鍵。
請問,問題解決了嗎?
按著你的語法做測試
只有這行不行Response.Write("gv 第1個欄位裡,按鈕的文字: " + ((Button)GridView1.Rows[GridView1.SelectedIndex].Cells[6].FindControl("Button")).Text + "<br>");
把它改成Response.Write("gv 第八個欄位裡,按鈕的文字: " + ((Button)GridView1.Rows[GridView1.SelectedIndex].Cells[6].Controls[0]).Text + "<br>");
就可以了