简体   繁体   中英

System.ArgumentOutOfRangeException: 'Index was out of range. Must be non-negative and less than the size of the collection.'

protected void getSUM()
{
    // SQL query that gets total of product sales where category id = 1
    string SqlQuery = @"SELECT Price AS TotalSales 
  FROM STOCK
  WHERE Barcode = '" + TextBox1 + "'";

    // Declare and open a connection to database


    sqlcon.Open();

    // Creates SqlCommand object
    SqlCommand comm = new SqlCommand(SqlQuery, sqlcon);

    // Gets total sales
    decimal TotalSales = Convert.ToDecimal(comm.ExecuteScalar());

    // Close connection
    sqlcon.Close();

    // Adds formatted output to GridView footer
    GridView1.Columns[3].FooterText = String.Format("{0:c}", TotalSales);
}

i just want to add the price at the footer of the gridview. i don't understand what's wrong. the error is in this line GridView1.Columns[3].FooterText = String.Format("{0:c}", TotalSales);

You are probably using AutoGenerateColumns="true" in your GridView. When using this you will only have access to the columns in the RowCreated and RowDataBound events. When the grid is done building the column count will be 0.

Better use TemplateFields. You'll have much more control that way.

<asp:GridView ID="GridView1" runat="server">
    <Columns>
        <asp:TemplateField>
            <ItemTemplate>
                <%# Eval("myColumn") %>
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>

Now GridView1.Columns.Count will return 1 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM