Error: Specified argument was out of the range of valid values. in RowDataBound Gridview

Error: Specified argument was out of the range of valid values. in RowDataBound Gridview

我想要绑定数据 gridview 并将数据“0”更改为“-”。 但错误:指定的参数超出了有效值的范围。参数名称:index

代码asp

 <asp:GridView ID="GridView1" runat="server" 
  AutoGenerateColumns="False" AllowPaging="true" 
  OnRowCreated="GridView1_RowCreated"  
  OnRowDataBound="GridView1_RowDataBound" >
   <Columns>
     <asp:BoundField DataField="amt" HeaderText="Total" 
          DataFormatString="{0:#,##0.00000}" ItemStyle-HorizontalAlign="Right" />
   </Columns>               
 </asp:GridView>

代码 C#

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
      {
          if (e.Row.RowType == DataControlRowType.DataRow)
          {                
             string sAmt = DataBinder.Eval(e.Row.DataItem, "amt").ToString();    

          if (sAmt == "0.00000")
          {
             e.Row.Cells[10].Text = "-"; <<< Line Error
          }
     }
 }

如果字段 AMT 显示 0。

我想要从“0”到“-”。

请帮帮我。感谢提前抽出时间。 ;)

是10的索引在:

e.Row.Cells[10].Text = "-"; <<< Line Error

有效吗?我的意思是数组中有 11 个项目,您可能正在尝试访问数组范围之外的内容。

错误消息告诉您在 GridView 中没有索引为 10 的单元格。确保 Cells 数组足够大。 可能应该试试

e.Row.Cells[e.Row.Cells.Length-1].Text = "-";

首先检查所选行中是否存在第 9 列(即 e.Row.Cells[10] 从 0 开始)。

如果您想在 GridView 单元格中显示特定值,请使用下面的方法 TemplateField of Gridview

 <asp:TemplateField HeaderText="Gender">
         <ItemTemplate>
               <asp:Label runat="server" Text='<% #GetLangID(Eval("langid2")) %>' />
         </ItemTemplate>
 </asp:TemplateField>

这将是您的代码隐藏

public string GETLangID(object dataItem)
{
    string text = string.Empty;
    int? val = dataItem as int?;
    switch (val)
    {
        case 0:
            text = "-";
            break;
        case 1:
            text = "One";
            break;
        case 2:
            text = "two";
            break;

    }
    return text;
}