January 22nd, 2011

Bind array to specific column of asp.net gridview

The object is to bind an array to particular column of asp.net gridview. Suppose we have a grid having 3 columns and an array say “data“. Now we have to bind data array to grid’s second column (binded by mycolumn). See following html code:


———————————————————
<asp:GridView ID="GridViewTest" runat="server"
AutoGenerateColumns="False">
<Columns>
<asp:TemplateField HeaderText="Select">
<ItemTemplate>
<asp:CheckBox ID="CheckBox1" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="myColumn" HeaderText="TestColumn"/>
<asp:TemplateField HeaderText="Cost">
<ItemTemplate>
<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
———————————————————
We can bind data array to second column very easily using Linq. See following c# code:
———————————————————
String[] data = { "test-1", "test-2", "test-3", "test-4", "test-5" };
GridViewTest.DataSource = from d in data
select new { myColumn = d };
GridViewTest.DataBind();

———————————————————
asp.net gridview data bind

Hope, It helps.