[英]How to dynamically retrieve the column index, id and the row index of a row in gridview
我有一個動態創建的grdview,其中包含4
列和n
行。 每列都有一個具有不同Id
的Button
控件。 該控件具有Click
事件。 事件觸發時,我想在運行時找到row
索引和cell
格索引或該按鈕的Id
本文將解釋如何使用JavaScript獲取ASP.Net GridView行及其RowIndex客戶端。 我還將說明如何使用JavaScript在GridView模板字段客戶端中找到GridView單元和控件。
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script type = "text/javascript">
function GetSelectedRow(lnk) {
var row = lnk.parentNode.parentNode;
var rowIndex = row.rowIndex - 1;
var customerId = row.cells[0].innerHTML;
var city = row.cells[1].getElementsByTagName("input")[0].value;
alert("RowIndex: " + rowIndex + " CustomerId: " + customerId + " City:" + city);
return false;
}
</script>
</head>
<body>
<form id="form1" runat="server">
<asp:GridView ID="gvCustomers" runat="server" AutoGenerateColumns = "false" AllowPaging = "true" OnPageIndexChanging = "PageIndexChanging">
<Columns>
<asp:BoundField DataField = "CustomerID" HeaderText = "CustomerID" />
<asp:TemplateField HeaderText = "City">
<ItemTemplate>
<asp:TextBox ID="txtCity" runat="server" Text = '<%# Eval("City") %>'></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="lnkSelect" runat="server" Text="Select" CommandName = "Select" OnClientClick = "return GetSelectedRow(this)" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</form>
</body>
</html>
找到行的索引,您可以簡單地做到這一點
GridViewRow gvr = e.Row;
要么
int index = Convert.ToInt32(e.RowIndex);
並找到控件的值,例如文本框的文本,您可以執行此操作
Label lb_ID = (TextBox)GridInvoice.Rows[index].Cells[1].FindControl("Label_ID");
其中index是行索引,cell [1]是單元索引,即,如果您的網格中有4個單元,則索引從cell [0] ... cell [3]開始。 這里cell [1]表示控制在ur grid的單元2中。 如果您有綁定表格數據庫的網格值,並且您還擁有一些唯一的ID(例如主鍵),並且您正在對該數據庫中的值執行操作,則從Frond端將此屬性添加到gridview(DatakeyNames =“ ur主鍵或uniqe值格式數據庫”;現在,如果您具有按鈕或鏈接按鈕控件(或在網格視圖中引發事件的任何其他控件,則在事件上編寫此代碼,它將自動捕獲u的主鍵和行索引。
protected void lnkbtnEdit_Click(object sender, EventArgs e)
{
GridViewRow gvrows = ((LinkButton)sender).NamingContainer as GridViewRow;
int32 Key = (Convert.ToInt32(grvCityList.DataKeys[gvrows.RowIndex].Values[0].ToString()));
Now do ur logic here
}
希望你能得到你想要的東西
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.