user2040600
user2040600

Reputation: 125

How to bind a List<string> to GridView in ASP.NET?

I am hitting an API and storing the returned parsed data to a List. Currently I am displaying the data in the ListView. I am not able display the same list in a GridView. Can anyone guide me how to do it?

This is my aspx.cs code:

    protected void Page_Load(object sender, EventArgs e)
    {
        ComodityList obj_comodity_in = (ComodityList)Session["comodity_list"];
        Label1.Text = obj_comodity_in.status_code;
        Label2.Text = obj_comodity_in.count.ToString();

        //ComodityList obj_comodity_in = (ComodityList)Session["comodity_list"];

        List<String> commodity_names = null;
        getComodityNames(out commodity_names, obj_comodity_in);
        ListView1.DataSource = commodity_names;
        ListView1.DataBind();   
    }
    private void getComodityNames(out List<String> commodity_names, ComodityList cl)
    {
        commodity_names = new List<string>();
        foreach (Commodity c in cl.data)
        {
            commodity_names.Add(c.commodity);
            commodity_names.Add(c.state);
            commodity_names.Add(c.market);
            commodity_names.Add(c.Maximum_Price.ToString());
            commodity_names.Add(c.Minimum_Price.ToString());
            commodity_names.Add(c.Modal_Price.ToString());
            commodity_names.Add(c.origin);
            commodity_names.Add(c.unit);
            commodity_names.Add(c.variety);


        }
    }

Upvotes: 0

Views: 5413

Answers (2)

Iswanto San
Iswanto San

Reputation: 18569

Set AutoGenerateColumns property to true will help you.

Default.aspx:

 <asp:GridView ID="GridView1" runat="server" Width="95%" autogeneratecolumns = "false">

Default.aspx.cs:

public partial class _Default : Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        List<string> s = new List<string>() { "a", "b", "c" };
        this.GridView1.DataSource = s;
        this.GridView1.DataBind();
    }
}

Upvotes: 1

Neil Thompson
Neil Thompson

Reputation: 6425

If you don't want to change the API (you still want to return a list of strings) and need to use a grid you could create a new class containing the properties you already had in Commodity and simply rehydrate the class using the lists string data. Each new 'Commodity' class could go in a new List<Commodity> and you can bind that to the grid.

On the other hand - it's probably better to reconsider what you are actually trying to achieve and then redesign the API if that is an option.

Upvotes: 0

Related Questions