在Gridview外部获取Gridview RowIndex
本文关键字:Gridview RowIndex 获取 外部 | 更新日期: 2023-09-27 18:24:14
我的按钮1在面板内,我想访问行索引,以便隐藏该图像按钮。但当我进入调试模式时,GridView1.SelectedIndex的值为null。救命!
protected void Button1_Click1(object sender, EventArgs e)
{
foreach (GridViewRow row in GridView1.Rows)
{
if (row.RowType == DataControlRowType.DataRow)
{
if (row.RowIndex == Convert.ToInt32(GridView1.SelectedIndex))
{
ImageButton StopButton = (ImageButton)row.FindControl("stopImageButton");
ImageButton StartButton = (ImageButton)row.FindControl("startImageButton");
StopButton.Visible = true;
StartButton.Visible = false;
}
}
}
this.StopTimeNotesPanel_ModalPopupExtender.Hide();
}
您说过Button在一个面板内。为了能够有效地处理GridView事件,请在GridView内部使用一个按钮。
或者,如果您仍然想使用面板中的按钮,那么,
1.)首先在Gridview中添加一个选择按钮。使用选择按钮和选择一行
2.)单击面板中的按钮。
只有当您选择了网格视图的一行时,才会设置GridView.SelectedIndex。有两种方法:
1.)将AutoGenerateSelectButton属性设置为true。
<asp:gridview id="CustomersGridView"
datasourceid="CustomersSource"
autogenerateselectbutton="True"
runat="server">
2.)为自己添加一个buttonField(位于网格的内部)View as:
<asp:gridview id="CustomersGridView"
datasourceid="CustomersSqlDataSource"
autogeneratecolumns="false"
runat="server">
<columns>
<asp:buttonfield buttontype="Button"
commandname="Select"
headertext="Select Customer"
text="Select"/>
<asp:boundfield datafield="CompanyName"
headertext="Company Name"/>
</columns>
</asp:gridview>
现在,选中一行后,将触发GridView的两个事件:在索引更改&已选择索引已更改。
仅在需要时,执行以下步骤以在SelctedIndexChangedEvent 中获取SelectedRow
void CustomersGridView_SelectedIndexChanged(Object sender, EventArgs e)
{
// Get the currently selected row using the SelectedRow property.
GridViewRow row = CustomersGridView.SelectedRow;
MessageLabel.Text = "You selected " + row.Cells[2].Text; // just for Display
}
现在,在您的按钮点击事件中,获取选定的索引:
protected void Button1_Click1(object sender, EventArgs e)
{
int i = CustomersGridView.SelectedIndex;
}
用于foreach
循环的代码:
ImageButton StopButton = (ImageButton)row.FindControl("stopImageButton");
ImageButton StartButton = (ImageButton)row.FindControl("startImageButton");
StopButton.Visible = true;
StartButton.Visible = false;