Home > Mobile >  How to display each string items in GridView?
How to display each string items in GridView?

Time:11-27

Here are some string items:

string[] r = {"item1","item2", "item3"}

I want to loop through GridView and add each string items to the GridView rows

for (int i = 0; i < GridView1.Rows.Count; i  )
    {
         GridView1.Rows[i].Cells[0].Text  = r[i];

    }

The GridView doesnt display any data... What method should use to solve this problem?

CodePudding user response:

See if this works for you. Forget the loop, data-enabled controls like this are better suited to data binding than dealing with the rows directly.

gridview1.DataSource = r;
gridview1.Databind();

CodePudding user response:

Ok, so with this markup:

<asp:GridView ID="GridView1" runat="server" Width="300px">

</asp:GridView>

then code behind is this:

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


    void LoadData()
    {

        string[] r = { "item1", "item2", "item3" };
        GridView1.DataSource = r;
        GridView1.DataBind();

    }

And we now get this:

enter image description here

However, as a general rule, you have to feed the gv a "structured" list of data.

So, that means "columns" or at least each row needs to have a "define" of the data.

We can change the above code to this:

    struct MyName
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string CodeName { get; set; }
        public MyName(string firstName, string lastName, string sCode)
        {
            FirstName = firstName;
            LastName = lastName;
            CodeName = sCode;
        }
    }

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


    void LoadData()
    {

        List<MyName> MyNames = new List<MyName>();

        MyNames.Add(new MyName("Clark", "Kent", "Superman"));
        MyNames.Add(new MyName("Peter", "Parker", "Spiderman"));
        MyNames.Add(new MyName("Bruce", "Wayne", "Batman"));
        MyNames.Add(new MyName("Tony", "Stark", "Ironman"));

        GridView1.DataSource = MyNames;
        GridView1.DataBind();
    }

And now we see/get this:

enter image description here

So, in most cases, you can't JUST send a list of strings, but a list with a "structure" that then becomes the column(s) for the grid view.

  • Related