【问题标题】:Error: Specified argument was out of the range of valid values. in RowDataBound Gridview错误:指定的参数超出了有效值的范围。在 RowDataBound 网格视图中
【发布时间】:2015-11-26 08:24:35
【问题描述】:

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

代码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”改为“-”。

请帮帮我。提前感谢您的时间。 ;)

【问题讨论】:

  • gridview 中有 10 个单元格吗?请显示标记

标签: c# asp.net gridview error-handling rowdatabound


【解决方案1】:

是10的索引:

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

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

【讨论】:

  • 这应该是一条评论
  • 抱歉,我后来想到了这个,这更像是一个引导性问题而不是一个答案,我打算根据他的回复更新这个,但我知道你来自哪里。
  • 我试试数组。它的 0.0000 有很多记录。我尝试新代码。现在它正在工作。谢谢这么多;)
【解决方案2】:

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

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

【讨论】:

  • 这不会占用预期的行,它总是在行的最后一个单元格中获取值
  • 是的。但这将始终有效(除非 Cells 是空数组)并且不会引发指定的异常。无论如何,主题代码中的问题 - 超出数组范围。如何解决 - 取决于隐藏的代码。
【解决方案3】:

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

如果您想在 GridView 单元格中显示特定值,请使用下面的 methis 和 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;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-10-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多