Home > Software engineering >  How to fill up a GridView with foreach loop
How to fill up a GridView with foreach loop

Time:11-28

I have this GridView markup:

        <asp:GridView ID="GridView1" runat="server" Width ="300px">
            <Columns>
                <asp:BoundField AccessibleHeaderText="TEXT" HeaderText="TEXT" />
            </Columns>
        </asp:GridView>

I want to fill up Gridview with some strings through foreach loop:

          foreach (GridViewRow row in GridView1.Rows)
        {
            string f = "this is looping";
            row.Cells[0].Text  = f;

        }

The problem is GridView1 doesn`t display anything...

CodePudding user response:

You can't use foreach loop becouse your GridView doesn't have data source. Set ObservableCollection as Source, and Add data to collection.

CodePudding user response:

Well, you can say have a gv like this:

        <asp:GridView ID="GridView1" runat="server" CssClass="table" Width="20%">

        </asp:GridView>

And then code:

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
            LoadGrid();
    }

    void LoadGrid()
    {

        List<string> MyList = new List<string> { "One", "Two", "Three" };
        GridView1.DataSource = MyList;
        GridView1.DataBind();


    }

And we get this:

enter image description here

Or, we can add a listitem (often used for a drop down list, or say listbox).

Thus:

        <asp:GridView ID="GridView1" runat="server" CssClass="table" 
            Width="20%" AutoGenerateColumns="false">
            <Columns>
                <asp:BoundField HeaderText="My header"
                    DataField="Text"/>
            </Columns>
        </asp:GridView>

(note how we turned off autogen colums)

code:

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
            LoadGrid();
    }

    void LoadGrid()
    {

        List<ListItem> MyList = new List<ListItem>();

        MyList.Add(new ListItem("One"));
        MyList.Add(new ListItem("Two"));
        MyList.Add(new ListItem("Three"));

        GridView1.DataSource = MyList;
        GridView1.DataBind();

    }

And we now have this:

enter image description here

So, you can use a simple string list, or even a list item. You loop adding to the object, and THEN feed to the gv.

so, you can loop and build up something, but that thing is THEN bound to the gv.

  • Related