[英]How to access a selected Boundfield value from a GridView in code-behind
我見過類似的問題,但沒有一個答案能幫助我解決這個問題。 我有一個帶有只讀字段的 GridView,如下所示。
網格視圖:
<asp:GridView ID="GridView1" runat="server" AllowPaging="True"
AutoGenerateColumns="False" DataKeyNames="projectID"
DataSourceID="SqlDataSource1"
EmptyDataText="There are no data records to display."
PageSize="5" OnRowUpdating="GridView1_RowUpdating">
<Columns>
<asp:CommandField ShowDeleteButton="True" ShowEditButton="True"/>
<asp:BoundField DataField="prID" HeaderText="prID" SortExpression="prID"/>
<asp:BoundField DataField="projectName" HeaderText="projectName"
SortExpression="projectName" />
<asp:BoundField DataField="projectType" HeaderText="projectType"
SortExpression="projectType" />
</Columns>
<EditRowStyle CssClass="GridViewEditRow"/>
</asp:GridView>
如您所見, prID
BoundField 具有Readonly=True
屬性。 當用戶更新行中的其他字段時,我試圖在代碼隱藏中獲取prID
的值。
代碼隱藏:
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
GridViewRow row = GridView1.Rows[e.RowIndex];
String d1 = ((TextBox)(row.Cells[2].Controls[0])).Text;
String d2 = ((TextBox)(row.Cells[3].Controls[0])).Text;
// this only works while the field is not readonly
string prIDUpdate = ((TextBox)(row.Cells[1].Controls[0])).Text;
}
注:我已經嘗試使用GridView1.DataKeys[e.RowIndex]
也onRowDataBound
的d設置綁定列俱備只在代碼隱藏,但我一直沒能得到結果
提前致謝!
我看到你在GridView控件中的DataKeyNames設置是這樣的
DataKeyNames="projectID"
那么我猜你的鍵名是projectID而不是prID ,不是嗎? 如果是這樣,您可以獲得所選行的數據作為這一行:
string id = GridView1.DataKeys[e.RowIndex]["projectID"].ToString();
您還應該添加此列:
<asp:BoundField DataField="projectID" HeaderText="prID" SortExpression="projectID"/>
你試過嗎?
換句話說,您可以嘗試使用 TemplateField 代替
<Columns>
<asp:TemplateField HeaderText="prID" SortExpression="prID">
<ItemTemplate>
<asp:Label ID="lblPrId" runat="server" Text='<%# Bind("prID") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="projectName" HeaderText="projectName"
SortExpression="projectName" />
<asp:BoundField DataField="projectType" HeaderText="projectType"
SortExpression="projectType" />
</Columns>
此代碼用於從 GridView1_RowUpdating 事件處理程序中的 prID 列獲取數據:
Label lblPrId = row.FindControl("lblPrId") as Label;
string prId = lblPrId .Text;
對不起,如果這沒有幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.