Dynamic BoundField in a gridview

C

Chicagoboy27

I have dynamically bound a field to a gridview using the follwoing
code:

BoundField nameColumn = new BoundField();

nameColumn.DataField = "territory";
nameColumn.HeaderText = "Terr Num";
nameColumn.SortExpression = "territory";

//appends the column at the end
GridView1.Columns.Add(nameColumn);
//Use insert command to notify what column number you would like it at
//GridView1.Columns.Insert(2, nameColumn);




in the gridview I have a template field in the grid..

<asp:TemplateField HeaderText="Name" SortExpression="last_name">
<ItemTemplate>
<asp:Label runat="server" ID="lblLastName"
Text='<%# Eval("last_name")%>'></asp:Label>,
<asp:Label ID="lblFirstName" runat="server"
Text='<%# Eval("first_name")%>'></asp:Label>
&nbsp;
<asp:Label ID="lblMidName" runat="server" Text='<%#
Eval("mid_name")%>'></asp:Label>
</ItemTemplate>



I am running into a problem when I try and grab the values of the
template fields using the following code on the selectedindexchanged.
The code below only works when I use GridView1.Columns.Add(nameColumn);
when I try and use
GridView1.Columns.Insert(2, nameColumn);
the code below does not want to work. I am wondering how to dynamically
create the bound column and have it work as the column.add function:

string name =
Convert.ToString(((Label)GridView1.SelectedRow.FindControl("lblLastName")).Text);
name = name + ", " +
Convert.ToString(((Label)GridView1.SelectedRow.FindControl("lblFirstName")).Text);


The error I receive when using columns.insert is

Object reference not set to an instance of an object.

any bump in the right direction would be appreciated
 
C

Chicagoboy27

Well i ended up figureing out a solution for now but would still like
to know how to do that in the future if need be.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,581
Members
45,057
Latest member
KetoBeezACVGummies

Latest Threads

Top