john
john

Reputation: 45

Unable to get value from list inorder to set Grid header value c#

I am trying to set grid header value from list getting error

Object Reference not set to an instance of an object

I check it first but I am converting list value to string and while debugging I can find value in list

code is given below,

        List<string> rows = new List<string>(
new string[] { "Item", "Quantity", "Price" });

                GdItemList.HeaderRow.Cells[0].Text = Convert.ToString(rows[0]);
                GdItemList.HeaderRow.Cells[1].Text = rows[1].ToString();
                GdItemList.HeaderRow.Cells[2].Text = rows[2].ToString();

GdItemList Grid view is like ,

<asp:GridView ID="GdItemList" runat="server" ShowHeaderWhenEmpty="True" CellPadding="4"
                    EmptyDataText="No Record Found" ForeColor="#333333" GridLines="None">
                    <AlternatingRowStyle BackColor="White" />
                    <EditRowStyle BackColor="#2461BF" />
                    <FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
                    <HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
                    <PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
                    <RowStyle BackColor="#EFF3FB" />
                    <SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
                    <SortedAscendingCellStyle BackColor="#F5F7FB" />
                    <SortedAscendingHeaderStyle BackColor="#6D95E1" />
                    <SortedDescendingCellStyle BackColor="#E9EBEF" />
                    <SortedDescendingHeaderStyle BackColor="#4870BE" />
                </asp:GridView>

Upvotes: 1

Views: 59

Answers (3)

I A Khan
I A Khan

Reputation: 8859

List<string> rows = new List<string>(
    new string[] { "Item", "Quantity", "Price" });

GdItemList.Columns[0].HeaderText = Convert.ToString(rows[0]);
GdItemList.Columns[1].HeaderText = rows[1].ToString();
GdItemList.Columns[2].HeaderText = rows[2].ToString();

Upvotes: 2

FranzHuber23
FranzHuber23

Reputation: 4322

Did you try to use the ElementAt function? https://msdn.microsoft.com/en-us/library/bb299233(v=vs.110).aspx

List<string> rows = new List<string>(new string[] { "Item", "Quantity","Price"});

GdItemList.HeaderRow.Cells[0].Text = rows.ElementAt(0);

Upvotes: 0

Basti
Basti

Reputation: 517

The problem is not with your List of strings but with your GdItemList. There is no error in the code you have shown us: https://repl.it/Njj3/0

Upvotes: 1

Related Questions