How to combine multiple lists and use as a GridView datasource

ASP.net:

<asp:GridView ID="gvSP" runat="server" AutoGenerateColumns="true">
</asp:GridView>

Code-behind:

lstName.Add(lstN[f]); //name
lstCMSID.Add(lstNum[f]); //number
lstSpecialtyPhys.Add(data.Text.ToString()); //value

I would like to combine the three List and display it in the above GridView, like this:

Name                        Number              Value
John Doe                    56                  90
James Coon                  34                  24

How can I achieve the above so there are three columns with three different header text.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

The simple way would be to do a loop (a for, foreach, etc)

        List<dynamic> lstName = new List<dynamic>();
        List<dynamic> lstCMSID = new List<dynamic>();
        List<dynamic> lstSpecialtyPhys = new List<dynamic>();

        lstName.Add("John Doe");
        lstCMSID.Add("56");
        lstSpecialtyPhys.Add("90");

        lstName.Add("James Coon");
        lstCMSID.Add("34");
        lstSpecialtyPhys.Add("24");

        DataTable dt = new DataTable();
        dt.Columns.Add("Name");
        dt.Columns.Add("Number");
        dt.Columns.Add("Value");

        for (int i = 0; i < lstName.Count; i++)
        {
            dt.Rows.Add(lstName[i], lstCMSID[i], lstSpecialtyPhys[i]);
        }

        gvSP.DataSource = dt;
        gvSP.DataBind();

Method 2

create a class as

private class ABC{  
string name ="";  
int number=0,val=0;  
    public string name1 {
    get { return name; }
    set { name = value; }
}
public int number1 {
    get { return number; }
    set { number = value; }
}
public int value1 {
    get { return val; }
    set { val = value; }
}
}

Add the below code in the code behind

var source = new BindingSource();
ArrayList dataobj = new ArrayList();
ABC obj = new ABC();
obj.name="Sample"  
obj.number=1
obj.value=5 
dataobj.add(obj);  
source.DataSource = dataobj;
DataGrid.DataSource = source;
DataGrid.Columns(0).Name="Desired Name" // So On for the Rest, to set desired name to the header

Hope it helps

Method 3

You can create a DataTable and put your data in it then bind the table to your grid.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x