[英]I can't find row in gridview's RowDataBound, gives exception“Index was out of range. Must be non-negative and less than the size of the collection.”
i am working with gridview
, i want change color of specific row into grid view thats why i must find row at rowdatabound event. 我正在使用
gridview
,我想将特定行的颜色更改为网格视图,这就是为什么我必须在rowdatabound事件中找到行的原因。 How i find the row? 我如何找到行?
Source code: 源代码:
protected void Page_Load(object sender, EventArgs e)
{
string[] arr={"1","2","3","4"};
GridView1.DataSource = arr;
GridView1.DataBind();
}
protected void pagechangin(object sender, GridViewPageEventArgs e) {
GridView1.PageIndex = e.NewPageIndex;
}
protected void databound(Object sender, GridViewRowEventArgs e) {
GridViewRow grv=GridView1.Rows[0];
}
You must register an event-handler to handle an event. 您必须注册事件处理程序才能处理事件。 But you haven't shown us the aspx markup, so maybe you have missed to add the handler declaratively:
但是您尚未向我们显示aspx标记,因此也许您错过了声明式添加处理程序的方法:
<asp:gridview id="GridView1"
onrowdatabound="GridView1_RowDataBound"
runat="server">
</asp:gridview>
void GridView1_RowDataBound(Object sender, GridViewRowEventArgs e)
{
if(e.Row.RowType == DataControlRowType.DataRow)
{
// e.Row is the GridViewRow
e.Row.BackColor = System.Drawing.Color.Green;
}
}
Update The reason for the IndexOutOfRangeException
is that you are accessing the first row before it is created: 更新
IndexOutOfRangeException
的原因是您要在创建第一行之前对其进行访问:
GridViewRow grv=GridView1.Rows[0];
This is a nasty one. 这是一个讨厌的人。
RowDataBound
is called for every GridViewRow
, not only for the DataItems
but also for the Header
, Footer
and Pager
. 每个
GridViewRow
都将调用RowDataBound
,不仅为DataItems
调用,还为Header
, Footer
和Pager
调用。 The first one that will be created is the Header
. 将创建的第一个是
Header
。 But GridView.Rows
does return only GridViewRows
with RowType
= DataRow
. 但是
GridView.Rows
确实仅返回RowType
= DataRow
GridViewRows
。 So you are trying to access the first "data-row" during the creation of the header
row. 因此,您试图在创建
header
行期间访问第一个“数据行”。
To fix it use the code above and check the RowType
. 要解决此问题,请使用上面的代码并检查
RowType
。
if(e.Row.RowType == DataControlRowType.DataRow)
{
// now you ca safely access the first row in this way,
// altghough i assume that you should use my code above
// to set the color of every GridViewRow
GridViewRow grv=GridView1.Rows[0];
Apart from that you should also DataBind
the grid only if(!IsPostBack)
as Dragan has mentioned if you're using ViewState
(default). 除此之外,如果您使用的是
ViewState
(默认值),则也应仅由Dragan提到的if if(!IsPostBack)
来DataBind
网格。
Your page_load event handler is not correct. 您的page_load事件处理程序不正确。 Yoou shouldn't load the data on every page load but only on the initial.
您不应该在每次页面加载时都加载数据,而应该仅在初始页面上加载。 Maybe this is causing problems.
也许这引起了问题。
Try this in your Page_Load method 在您的Page_Load方法中尝试
if (!Page.IsPostback)
{
//copy your code from above
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.