Reputation: 19
protected void BindGV()
{
List<List<string>> list = new List<List<string>>()
{
new List<string>() {"Hussain","IT","Hyderabad" },
new List<string>() { "Sharief","IT","Bangalore"},
new List<string>() { "Shaik","IT","Chennai"}
};
gv1.DataSource = list;
gv1.DataBind();
}
I want to display only Name and City in Gridview. I want to use like:
<asp:Boundfield Datafield="" Headertext="Name"/>
How to use DataField in this case??
Upvotes: 0
Views: 4835
Reputation: 9296
First of all, you should create a List with some class, rather than string. Then you can use class properties in you DataGrid as columns.
For example:
public class Personnel
{
public string Name { get; set; }
public string Department { get; set; }
public string Location { get; set; }
}
Then you can create a data source like:
protected void BindGV()
{
List< Personnel > list = new List< Personal >()
{
new Personnel {Name = "Hussain", Department = "IT", Location = "Hyderabad" },
new Personnel {Name = "Sharief", Department = "IT", Location = "Bangalore"},
new Personnel {Name = "Shaik", Department = "IT", Location = "Chennai"}
};
gv1.DataSource = list;
gv1.DataBind();
}
In your code behind create DataGrid like
<asp:DataGrid runat="server" ID="gv1" AutoGenerateColumns="False>
<Columns>
<asp:BoundColumn HeaderText="Name" DataField="Name" />
<asp:BoundColumn HeaderText="Dept" DataField="Department" />
<asp:BoundColumn HeaderText="City" DataField="Location" />
</Columns>
</asp:DataGrid>
And that should be it.
UPDATE: According to you comment, you want to access DataField
programatically. You can do this by enumerating gv1.Columns
property and then cast the result to BoundColumn
. This will give you access to DataField
and other properties.
Upvotes: 4
Reputation: 17614
You can take benefit of linq
List<List<string>> list = new List<List<string>>()
{
new List<string>() {"Hussain", "IT", "Hyderabad"},
new List<string>() {"Sharief", "IT", "Bangalore"},
new List<string>() {"Shaik", "IT", "Chennai"}
};
linq query
var v = from li in list select new {Name = li[0], City=li[2]};
gv1.DataSource = v;
gv1.DataBind();
And gridview
<asp:DataGrid runat="server" ID="gv1" AutoGenerateColumns="False>
<Columns>
<asp:BoundColumn HeaderText="Name" DataField="Name" />
<asp:BoundColumn HeaderText="City" DataField="City" />
</Columns>
</asp:DataGrid>
But this is not a good Idea to use.
You should have a proper structure of you property as suggested by the two gentle men.
Upvotes: 0
Reputation: 1007
as Husein said, first create class with Get , Set . like
Public class BindGV
{
public string name { get; set ;}
public string Profile { get; set ;}
public string loc { get; set ;}
}
In aspx page Gridview BoundField....
<ItemTemplate..>
<b><%# DataBinder.Eval(Container, "DataItem.Title") %> </b>
<br />
<%# DataBinder.Eval(Container, "DataItem.Description") %>
</ItemTemplate>
... Or Apsx.cs code
BindGV.datasource=object.GetDetails();
BindGV.dataBind();
Upvotes: 1