views:

504

answers:

2

Im trying to add data into a new column I have created in my gridview. I create the column with the code below:

Dim Field As New BoundField
Field.HeaderText = "Cummulative Amount"
Dim Col As DataControlField = Field
Me.GridView1.Columns.Add(Col)

Now I need to go in and add data for the rows below the column. I have seen ppl saying I need to set it equal to a datafield but how do I create a datafield from scratch then?

Thanks in advance,

+2  A: 

Yes, people have told you the correct thing - You need to set the DataField property of a BoundField in order for it to be rendered. Your DataField would be a public property exposed by the Datasource you bind your GridView to.

As a side point, you don't need to create a DataControlField because the BoundField class inherits from DataControlField. You can directly add the BoundField to the Columns collection of the GridView.

Dim Field As New BoundField()
Field.HeaderText = "Cumulative Amount"
Field.DataField = "CumulativeAmount"

Me.GridView1.Columns.Add(Field)
Cerebrus
+1  A: 

Update:

You can create this calculated column right in the markup for the gridview. Assuming that your datasource has an Field named "Amount" and another field named "Quantity" and that your "Cummulative Amount" is a product of those two columns, you could do something like this:

<asp:GridView runat="server" DataSource="sqlDataSource">
  <columns>
    <asp:BoundField HeaderText="Amount" DataField="Amount" />
    <asp:BoundField HeaderText="Quantity" DataField="Quantity" />
    <asp:TemplateField HeaderText="Cummulative Amount">
      <ItemTemplate>
        <asp:Label runat="server" Text='<%# Eval("Amount") * Eval("Quantity") %>' >
      </ItemTemplate>
    </asp:TemplateField>
  </columns>
</asp:GridView>
Jose Basilio
Yes that's exactly what I am trying to do.
Splashlin
Are the other columns autogenerated or do you add them through markup?
Jose Basilio
I used the gridview wizard. They are all created from a table stored in the DB. I need to create these columns which are calculated values from the fields before it in the row.
Splashlin
I do know that the autogeneratescolumns property is set to false.
Splashlin
Thanks a lot for your help, one last question. If I need to get data from rows above the current one how would I accomplish this? For example if I want a column named Total Spend and the data in its cell is the cumulative addition of all of the rows under the Spent column including and before the row it is put on?
Splashlin
You need set ShowFooter="true" and handle the RowDataBound event for the grid to accumulate the values. Here's a link to a nice tutorial on that: http://www.asp.net/learn/data-access/tutorial-15-cs.aspx
Jose Basilio