• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 325
  • Last Modified:

GridView inserting column at run time

I have a GridView with dynamic data retrieved from the database. I want to add an extra column in the beginning adding an identity type column [sr no] either by code-behind or source code. I tried using a Template Column, but the first column from the database overrides that column and the sr. no generated displayed instead of the first column data from the database.

How should I do it? How should i add an extra column at runtime to display the srno?

This is the code for generating srno:

    Protected Sub GridView1_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GridView1.RowDataBound
            If e.Row.RowType <> DataControlRowType.Header Then
                e.Row.Cells(0).Text = Convert.ToString(e.Row.DataItemIndex + 1)
            End If
        End Sub
0
digitalZo
Asked:
digitalZo
  • 9
  • 7
1 Solution
 
NickWaltCommented:
OK I think I know what your saying. You want a column in the GridView that is updated via code. The way I do this is to create a template field at design time. Doesn't matter where the field is in the column order (don't think so anyway). Then switch to HTML view.

<asp:TemplateField HeaderText="Manufacturer" SortExpression="Manufacturer">
    <ItemTemplate>
        <%#GetManufacturer(Container.DataItem)%>
     </ItemTemplate>
 </asp:TemplateField>

Then go to you code behind page and add the following code:

    Protected Function GetManufacturer(ByVal ms As SPGProductsRecord) As String
        GetManufacturer = "RESULT GOES HERE"
    End Function

I have changed the code to be more relevent, but I normally send across the data row and do something in the code to generate the result. The result is then displayed in the template column.
0
 
digitalZoAuthor Commented:
But I'm using this code to update or to increment the count:

    Protected Sub GridView1_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GridView1.RowDataBound
            If e.Row.RowType <> DataControlRowType.Header Then
                e.Row.Cells(0).Text = Convert.ToString(e.Row.DataItemIndex + 1)
            End If
        End Sub


How do I call this in the Template field?
0
 
digitalZoAuthor Commented:
Hello NickWalt,

I tried your solution, but no luck. It did not generate the extra column at all.
0
VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

 
NickWaltCommented:
Hi, why do you need to create the column at run time. Do you have a special need for this. I normally create a template field in the grid and then populate the contents of the row item when the row is being read from the db and built into the grid.
0
 
digitalZoAuthor Commented:
Yeah, I have to insert a column [not necessarily at run time] to generate the serial number for the data. Your solution works with other web applications on which I've tested, but it doesn't work with this one.

Is it because I'm using a stored procedure in this one?
0
 
NickWaltCommented:
no i don't think so. your stored procedure which just return an SQL Table or View.

Tell me am I right in thinking that you have a table of data from stored procedure and you want to create through code some extra column which relates to the data?

I tell you how I have used this in the past. I want to have a grid view of data from a shopping cart, it displays all of the data correctly, but instead of the Product ID I was to show the product name (due to good database design). I inserted a template field and then called a function from my code behind which did a quick SQL query on the other table (could have used a join, but didn't). The code then simply returned the Product Name as a string, job done.

Am i misunderstanind your question perhaps.
0
 
digitalZoAuthor Commented:
<<you want to create through code some extra column which relates to the data?>>

The extra column displays the identity or serial number of the records. it's the most basic thing actually. this is an example:

SR.NO      DATA1  DATA2
--------      --------   --------
1               text       text
2               text       text
3               text       text

the serial number is what i've to code or autogenerate.
0
 
NickWaltCommented:
There is a simpler answer to this, if you are using a stored procedure, why don't you create a column ther as in identity field. I have seen this done somewhere to help with custom paging in the gridview control.

This article would be a start for this:
http://dotnetjunkies.com/Tutorial/EA868776-D71E-448A-BC23-B64B871F967F.dcik

OK. I have started a new form. Dropped Grid onto and connected to SQL Table (could be stored procedure). Have a function to add a sequential number to the record as seen below:

Does this help?



<%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default.aspx.vb" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="JobID"
            DataSourceID="SqlDataSource1">
            <Columns>
                <asp:TemplateField HeaderText="Ser No">
                    <ItemTemplate>
                        <%#GetSerialNo(Container.DataItem)%>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:BoundField DataField="JobID" HeaderText="JobID" InsertVisible="False" ReadOnly="True"
                    SortExpression="JobID" />
                <asp:BoundField DataField="UserID" HeaderText="UserID" SortExpression="UserID" />
                <asp:BoundField DataField="FarmName" HeaderText="FarmName" SortExpression="FarmName" />
                <asp:BoundField DataField="FieldName" HeaderText="FieldName" SortExpression="FieldName" />
                <asp:BoundField DataField="OperatorName" HeaderText="OperatorName" SortExpression="OperatorName" />
                <asp:BoundField DataField="Operation" HeaderText="Operation" SortExpression="Operation" />
                <asp:BoundField DataField="Vehicle" HeaderText="Vehicle" SortExpression="Vehicle" />
                <asp:BoundField DataField="Implement" HeaderText="Implement" SortExpression="Implement" />
                <asp:BoundField DataField="Width" HeaderText="Width" SortExpression="Width" />
                <asp:BoundField DataField="StartOfJob" HeaderText="StartOfJob" SortExpression="StartOfJob" />
                <asp:BoundField DataField="EndOfJob" HeaderText="EndOfJob" SortExpression="EndOfJob" />
                <asp:BoundField DataField="XMLFileName" HeaderText="XMLFileName" SortExpression="XMLFileName" />
            </Columns>
        </asp:GridView>
        <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:WebGISDB %>"
            SelectCommand="SELECT * FROM [WebGISJobList]"></asp:SqlDataSource>
   
    </div>
    </form>
</body>
</html>


Partial Class _Default
    Inherits System.Web.UI.Page
    Public SerNoCount As Long = 1

    Public Function GetSerialNo(ByVal mm As Data.DataRowView) As String
        GetSerialNo = SerNoCount.ToString
        SerNoCount = SerNoCount + 1
    End Function
End Class
0
 
digitalZoAuthor Commented:
Thanks for your help but I'm not binding any columns in the source code because the data generated is dynamic. Also, if I add a column to one stored procedure, I'll have to add in ALL which means there'll be again some clashes and more errors et al and there are about 20-25 stored procedures.

Isn't there any simpler way to do this?
0
 
NickWaltCommented:
when you say the data is dynamic, how is it generated. i think this is the bit i'm missing.
0
 
digitalZoAuthor Commented:
Data being dynamic means that data is different for different reports. Because of this I cannot define the columns because different reports have different columns.

Hope this much info helps. If you need more info, do ask.
0
 
NickWaltCommented:
ok, there is another way which involves writing some classes. With larger database project the normal procedure is to seperate off the database and the web pages. This is called n-tier architechture. Normally you would have a class called the Business Layer Logic (BLL) which interfaces with the top layer Web Page. This has the Business Logic and this would be I guess where you could add your extra column through code. Under this you have a Data Access Layer (DAL), this has the actual SQL statements for Create, Select, Insert etc.

All of this can take a while to code up so I wrote a small program to build the BLL and DAL code within a single VB file. If you would like a copy send me your email address and I'll send you a link to the install. I use it all the time even on really small projects. It spits out between 500 and 1000 lines of code based on database structure and SQL statements.

That would be my recommendation. Let me know.
0
 
digitalZoAuthor Commented:
Thanks for the suggestion but it is in no way related to my problem. We are using BLL and DAL.I tried everything but somehow it doesn't work. I guess there's no solution for this.
0
 
NickWaltCommented:
in what way does this work? i add columns to my grids quite often for lookup values to table values.

Also using classes kind of makes sense cos you have acces to all of the code before the dataset is created.
0
 
digitalZoAuthor Commented:
The problem is I cannot define the columns and therefore when I do try to add a column at run-time, it overrides. There seems to be bug.

Thanks for your help though. Appreciated.
0
 
digitalZoAuthor Commented:
This is not the answer, but I'm allotting the points to you in case if anyone wants to know how to insert a column to data which is static.
0

Featured Post

Fill in the form and get your FREE NFR key NOW!

Veeam is happy to provide a FREE NFR server license to certified engineers, trainers, and bloggers.  It allows for the non‑production use of Veeam Agent for Microsoft Windows. This license is valid for five workstations and two servers.

  • 9
  • 7
Tackle projects and never again get stuck behind a technical roadblock.
Join Now