当点击一个按钮时,我试图从gridview获取所选行值并使用该值执行某些操作但我收到此错误:
Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index
并且代码在此行失败:
string category = gvDetail.Rows[rowIndex].Cells[0].Text;
这是我的代码:
<asp:GridView ID="gvDetail" runat="server" CssClass="table table-hover table-bordered table-responsive" ForeColor="#333333" GridLines="None"
CellPadding="4" PageSize="200" OnRowCommand="GridViews_RowCommand"
AutoGenerateColumns="false" AllowSorting="true" AllowPaging="true" EnableViewState="False">
<AlternatingRowStyle BackColor="#F3F3F3" />
<Columns>
<asp:BoundField DataField="Category" HeaderText="Category" />
<asp:BoundField DataField="name" HeaderText="Name" />
<asp:BoundField DataField="volume_paid" DataFormatString="{0:C0}" HeaderText="Spend" />
<asp:ButtonField HeaderText="Spend Metrics" ButtonType="Image" ImageUrl="~/img/mail.png" ControlStyle-Width="30px" ControlStyle-Height="30px" CommandName="Select" />
<asp:ButtonField HeaderText="Request Call/Meeting" ButtonType="Image" ImageUrl="~/img/mail.png" ControlStyle-Width="30px" ControlStyle-Height="30px" CommandName="Select1" />
</Columns>
<HeaderStyle CssClass="GridviewScrollHeader" BackColor="#1C5E55" Font-Bold="True" ForeColor="White" />
<RowStyle CssClass="GridviewScrollItem" ForeColor="#000066" />
</asp:GridView>
代码背后的代码:
protected void GridViews_RowCommand(object sender, GridViewCommandEventArgs e)
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["myConn"].ToString());
SqlDataAdapter da = new SqlDataAdapter(@"select min(month_key) as minKey, max(month_key) as maxKey from myTable", con);
DataTable dtSETS = new DataTable();
da.Fill(dtSETS);
if (dtSETS.Rows.Count > 0)
{
DataRow dtSETS_row = dtSETS.Rows[0];
int minKey = dtSETS_row.Field<int>("minKey");
int maxKey = dtSETS_row.Field<int>("maxKey");
if (e.CommandName == "Select")
{
///Determine the RowIndex of the Row whose Button was clicked.
int rowIndex = Convert.ToInt32(e.CommandArgument);
string category = gvDetail.Rows[rowIndex].Cells[0].Text;
string name = gvDetail.Rows[rowIndex].Cells[1].Text;
string volumepaid = gvDetail.Rows[rowIndex].Cells[2].Text;
// do something...
}
if (e.CommandName == "Select1")
{
// do something...
}
}
}
答案 0 :(得分:0)
问题是我将enableviewstate设置为false,所以我必须做的是将其设置为true。 感谢