CodeVerge.Net Beta


   Explore    Item Entry   Register  Login  
Microsoft News
Asp.Net Forums
IBM Software
Borland Forums
Adobe Forums
Novell Forums




Can Reply:  No Members Can Edit: No Online: Yes
Zone: > NEWSGROUP > Asp.Net Forum > general_asp.net.faq_frequently_asked_questions Tags:
Item Type: NewsGroup Date Entered: 8/23/2006 7:33:03 PM Date Modified: Subscribers: 0 Subscribe Alert
Rate It:
NR
XPoints: N/A Replies: 26 Views: 290 Favorited: 0 Favorite
27 Items, 2 Pages 1 2 |< << Go >> >|
Crouchin9Tiger
Asp.Net User
HOW TO: Build a dynamic gridView at runtime8/23/2006 7:33:03 PM

0

The following example demonstrates how to build a grid view dynamically at runtime.

 

' Get the connection string, In this case it's comming from the web.config file

Dim

strCon As String = System.Configuration.ConfigurationManager.ConnectionStrings("con").ConnectionString

Dim con As New SqlConnection(strCon)

Dim cmd As New SqlCommand("[SEL_Results]", con)

cmd.CommandType = Data.CommandType.StoredProcedure

Dim yourParameter As SqlParameter = cmd.Parameters.Add("@yourParameter", Data.SqlDbType.VarChar)

yourParameter.Value = theValue

'Setting the dataAdapter to the sqlCommand.

Dim da As New SqlDataAdapter(cmd)

Dim ds As New DataSet

Try

      con.open()

      da.Fill(ds)

Catch ex As Exception

Finally

      con.Close()

End Try

 

Dim dc As DataColumn

If ds.Tables.Count > 0 Then

      'Building all the columns in the table.

      For Each dc In ds.Tables(0).Columns

            Dim bField As New BoundField

            'Initalize the DataField value.

            bField.DataField = dc.ColumnName

            'Initialize the HeaderText field value.

            bField.HeaderText = dc.ColumnName

            'Add the newly created bound field to the GridView.

            grdView.Columns.Add(bField)

      Next

End If

'Setting the dataSource of the grid here.

grdView.DataSource = ds.Tables(0)

grdView.dataBind()

To add sorting and paging to the gridView take a look at this article written by StrongTypes:

http://forums.asp.net/thread/1177923.aspx

Enjoy!

 
keith.rull
Asp.Net User
Re: HOW TO: Build a dynamic gridView at runtime8/23/2006 9:40:56 PM

0

Crouchin9Tiger:

The following example demonstrates how to build a grid view dynamically at runtime.

 

' Get the connection string, In this case it's comming from the web.config file

Dim

strCon As String = System.Configuration.ConfigurationManager.ConnectionStrings("con").ConnectionString

Dim con As New SqlConnection(strCon)

Dim cmd As New SqlCommand("[SEL_Results]", con)

cmd.CommandType = Data.CommandType.StoredProcedure

Dim yourParameter As SqlParameter = cmd.Parameters.Add("@yourParameter", Data.SqlDbType.VarChar)

yourParameter.Value = theValue

'Setting the dataAdapter to the sqlCommand.

Dim da As New SqlDataAdapter(cmd)

Dim ds As New DataSet

Try

      con.open()

      da.Fill(ds)

Catch ex As Exception

Finally

      con.Close()

End Try

 

Dim dc As DataColumn

If ds.Tables.Count > 0 Then

      'Building all the columns in the table.

      For Each dc In ds.Tables(0).Columns

            Dim bField As New BoundField

            'Initalize the DataField value.

            bField.DataField = dc.ColumnName

            'Initialize the HeaderText field value.

            bField.HeaderText = dc.ColumnName

            'Add the newly created bound field to the GridView.

            grdView.Columns.Add(bField)

      Next

End If

'Setting the dataSource of the grid here.

grdView.DataSource = ds.Tables(0)

grdView.dataBind()

To add sorting and paging to the gridView take a look at this article written by StrongTypes:

http://forums.asp.net/thread/1177923.aspx

Enjoy!

 

i dont get this sample? why not just pass the dataset to the gridview? why not just customize the view for the data?

this approach seems like alot of overhead to me.


greatness is not about what you have accomplished! its about what you overcomed!
-
My Personnal Site | DevPinoy.org: A Filipino Developers Community
Crouchin9Tiger
Asp.Net User
Re: HOW TO: Build a dynamic gridView at runtime8/23/2006 11:51:09 PM

0

When you say why not just pass the gridView a dataset do you mean in the design view?  
Crouchin9Tiger
Asp.Net User
Re: HOW TO: Build a dynamic gridView at runtime8/24/2006 1:32:10 PM

0

Giving it a bit more thought perhaps I should have quantified my reason behind building a dynamic grid view.

If you have more than one procedures filling the grid view. Like if you were going to build a generic grid you used in a user control that had a different stored procedure with a different amount of columns with earch stored procedure you passed or a search grid that took a basic and advanced stored procedure; In which case you would substitute the portion a the top of my example with something like this.

dim sSQL as string

If type = "basic" then

   sSQL = "EXEC basicSearch  " & txtSearch.Text 

else

   sSQL = "EXEC advancedSearch " & txtTitle.Text & "," & ddlStatus.SelectedValue ... and so on.

end if

dim cmd as new SqlCommand(sSQL, con)

 

I hope this clears up any confusion anyone might have had.

keith.rull
Asp.Net User
Re: HOW TO: Build a dynamic gridView at runtime8/24/2006 4:51:21 PM

0

Crouchin9Tiger:

Giving it a bit more thought perhaps I should have quantified my reason behind building a dynamic grid view.

If you have more than one procedures filling the grid view. Like if you were going to build a generic grid you used in a user control that had a different stored procedure with a different amount of columns with earch stored procedure you passed or a search grid that took a basic and advanced stored procedure; In which case you would substitute the portion a the top of my example with something like this.

dim sSQL as string

If type = "basic" then

   sSQL = "EXEC basicSearch  " & txtSearch.Text 

else

   sSQL = "EXEC advancedSearch " & txtTitle.Text & "," & ddlStatus.SelectedValue ... and so on.

end if

dim cmd as new SqlCommand(sSQL, con)

 

I hope this clears up any confusion anyone might have had.

 

why not a basic gridview? then implement the Strategy-Factory Pattern combo to pass the necessary data to the grid since one your example you are not doing additional formatting to the data other than creating bound columns.

the data shouldnt be a requirement to implement a grid like your example since there is no formatting and because the gridview control can automatically adjust its columns bases on the data you pass to it.


greatness is not about what you have accomplished! its about what you overcomed!
-
My Personnal Site | DevPinoy.org: A Filipino Developers Community
vcsjones
Asp.Net User
Re: HOW TO: Build a dynamic gridView at runtime8/24/2006 5:45:34 PM

0

That is interesting, but how well does it keep up with things liked editing, adding, and deleting rows?
Cheers,
       Kevin Jones


Crouchin9Tiger
Asp.Net User
Re: HOW TO: Build a dynamic gridView at runtime8/24/2006 8:43:21 PM

0

I'm not sure what you mean by basic gridView and Strategy-Factory Patterns could you expain a little further?
Crouchin9Tiger
Asp.Net User
Re: HOW TO: Build a dynamic gridView at runtime8/24/2006 8:45:52 PM

0

vcsjones:
That is interesting, but how well does it keep up with things liked editing, adding, and deleting rows?

You would have to create the template columns at run-time as well. 

mbanavige
Asp.Net User
Re: HOW TO: Build a dynamic gridView at runtime8/24/2006 11:52:46 PM

0

Crouchin9Tiger:

Giving it a bit more thought perhaps I should have quantified my reason behind building a dynamic grid view.

If you have more than one procedures filling the grid view. Like if you were going to build a generic grid you used in a user control that had a different stored procedure with a different amount of columns with earch stored procedure you passed or a search grid that took a basic and advanced stored procedure; In which case you would substitute the portion a the top of my example with something like this.

dim sSQL as string

If type = "basic" then

   sSQL = "EXEC basicSearch  " & txtSearch.Text 

else

   sSQL = "EXEC advancedSearch " & txtTitle.Text & "," & ddlStatus.SelectedValue ... and so on.

end if

dim cmd as new SqlCommand(sSQL, con)

 

I hope this clears up any confusion anyone might have had.

The GridView already supports a boolean property named "AutoGenerateColumns".
When set to True, the GridView itself will automatically generate a grid column for each column in your datasource.


Mike Banavige
~~~~~~~~~~~~
Dont forget to click "Mark as Answer" on the post that helped you.
This credits that member, earns you a point and marks your thread as Resolved so we will all know you have been helped.
Crouchin9Tiger
Asp.Net User
Re: HOW TO: Build a dynamic gridView at runtime8/25/2006 1:18:40 PM

0

Completely forgot about that... That is a much easier way. Thanks for your input!
Crouchin9Tiger
Asp.Net User
Re: HOW TO: Build a dynamic gridView at runtime8/25/2006 1:56:11 PM

0

Based on mbanavige's feedback I have made an adjustment to the code I had earlier posted:

 

 Get the connection string, In this case it's comming from the web.config file

Dim strCon As String = System.Configuration.ConfigurationManager.ConnectionStrings("con").ConnectionString

Dim con As New SqlConnection(strCon)

dim sSQL as string

If type = "basic" then

   sSQL = "EXEC basicSearch  " & txtSearch.Text 

else

   sSQL = "EXEC advancedSearch " & txtTitle.Text & "," & ddlStatus.SelectedValue ... and so on.

end if

dim cmd as new SqlCommand(sSQL, con)

cmd.CommandType = Data.CommandType.StoredProcedure

'Setting the dataAdapter to the sqlCommand.

Dim da As New SqlDataAdapter(cmd)

Dim ds As New DataSet

Try

      con.open()

      da.Fill(ds)

Catch ex As Exception

Finally

      con.Close()

End Try

'Setting the dataSource of the grid here.

grdView.DataSource = ds.Tables(0)

grdView.AutoGenerateColumns = true

grdView.dataBind()

 

Much cleaner! Thanks again.

lconley
Asp.Net User
Re: HOW TO: Build a dynamic gridView at runtime9/19/2006 2:33:03 PM

0

Great peice of code, How would I make these col editable? ie text box...
Crouchin9Tiger
Asp.Net User
Re: HOW TO: Build a dynamic gridView at runtime9/19/2006 3:17:01 PM

0

I will be writing a follow up in regards to that bit of functionality.  Just not sure when I will have the time yet.. 

mbanavige
Asp.Net User
Re: HOW TO: Build a dynamic gridView at runtime9/19/2006 11:03:27 PM

0

lconley:
Great peice of code, How would I make these col editable? ie text box...

it's built-in...

http://msdn2.microsoft.com/en-us/library/system.web.ui.webcontrols.gridview.autogenerateeditbutton.aspx


Mike Banavige
~~~~~~~~~~~~
Dont forget to click "Mark as Answer" on the post that helped you.
This credits that member, earns you a point and marks your thread as Resolved so we will all know you have been helped.
bernhard@cedarc
Asp.Net User
Re: HOW TO: Build a dynamic gridView at runtime1/22/2007 6:18:05 AM

0

There is a problem with the AutoGenerateColumns feature.  When selected to true the GridView will populate, however, the GridView Column collection will not.

For example: With AutoGenerateColumns = true; GridView.Columns().Count will equal 0

So if you need to reference a column or need to know the count of  columns you can't.  I'm having to deal with this very issue in a web application I'm developing.  I need to control the width of the column according to displayed data and its wrap property.  The only way I could obtain this control was to build the bound fields dynamically as explained in the original posting.  Only then was I able to get the GridView Column collection to populate and work as though it was statically bound to a data control.


GLENN
vishwa
Asp.Net User
Re: HOW TO: Build a dynamic gridView at runtime2/12/2007 4:51:54 AM

0

This is an example on the same line, if you want to give a custom header or formatting to dynamic gridview at run time.

http://www.vishwamohan.com/ShowArticle.aspx?ArticleID=25

 

 


Vishwa


My Web Site and Blog
CSharpSean
Asp.Net User
Re: HOW TO: Build a dynamic gridView at runtime2/12/2007 6:12:21 AM

0

RSewell
Asp.Net User
Re: HOW TO: Build a dynamic gridView at runtime3/8/2007 9:55:52 PM

0

I'm not sure if the following will work for a GridView, but it works for a DataGrid:

If you'd rather not build the whole DataGrid by hand, prefering to let VS2005 do the grunt work with the drag'n'drop it does so well, but want to adjust a dataGridItem's attributes conditionally, you can do that as well.

For example, say you're displaying ProductName, UnitPrice and UnitsInStock from the Products table of the Northwind database in a DataGrid.  You want to change the text color of the cells to gray if the Discontinued field is true, and you want to change the background color of the item's row cells to red if the UnitsInStock is less than 10 as a visual cue to the operator to reorder more of those units.

So, with your datagrid (dgProducts) built on the web page into BoundColumns whose DataFields are ProductName, UnitPrice and UnitsInStock (in that order) and with Discontinued loaded into a fourth BoundColumn (hidden with Visible="false"), you can make those individual changes in the sub that loads your data, immediately after you bind the dataset to the grid's datasource, as follows:

dgProducts.DataSource = ds
dgProducts.DataBind()

Dim itm As DataGridItem
For Each itm In dgProducts
   If itm.Cells(3).Text = False Then
      itm.Cells(0).ForeColor = Drawing.Color.Gray
      itm.Cells(1).ForeColor = Drawing.Color.Gray
      itm.Cells(2).ForeColor = Drawing.Color.Gray
   End If
   If CInt(itm.Cells(2).Text) < 10 Then
       itm.Cells(2).BackColor = Drawing.Color.Red
   End If
Next

I don't know how useful that is to anyone else, but it sure helped me.  I'll have to play around and see if there's a way to do this with a GridView; so far I haven't found the DataView's equivalent to a DataGridItem.

utsavuce
Asp.Net User
Re: HOW TO: Build a dynamic gridView at runtime with Style5/17/2007 11:36:25 AM

0

Hi,

I am looking forward to build a complete gridview (with row style) as custom control .

e.g:

<asp:GridView ID="gridViewLoanDetails" runat="server" CssClass=Label AutoGenerateColumns="False" BackColor="White" BorderColor="#999999" BorderStyle="Solid" BorderWidth="1px" CellPadding="3" ForeColor="Black" GridLines="Vertical" AllowPaging="True" PageSize="30">

<Columns>

<asp:BoundField DataField="month" HeaderText="Month" />

<asp:BoundField DataField="scheduledBalance" HeaderText="Scheduled Balance" />

<asp:BoundField DataField="interest" HeaderText="Interest" />

<asp:BoundField DataField="principalPayed" HeaderText="Principal Payed" />

<asp:BoundField DataField="emi" HeaderText="EMI" />

<asp:BoundField DataField="apr" HeaderText="APR" />

</Columns>

<FooterStyle BackColor="#CCCCCC" />

<SelectedRowStyle BackColor="#000099" Font-Bold="True" ForeColor="White" />

<PagerStyle BackColor="#999999" ForeColor="Black" HorizontalAlign="Center" />

<HeaderStyle BackColor="Black" Font-Bold="True" Font-Size="Small" ForeColor="White" />

<AlternatingRowStyle BackColor="#CCCCCC" />

</asp:GridView>

How one can add Bound field and footer style etc. at runtime?

Thanks, 

 

sibush
Asp.Net User
Re: HOW TO: Build a dynamic gridView at runtime5/18/2007 10:32:33 AM

0

Sorry its working

27 Items, 2 Pages 1 2 |< << Go >> >|


Free Download:

Books:
Learning ASP.NET 3.5 Authors: Jesse Liberty, Dan Hurwitz, Brian MacDonald, Pages: 588, Published: 2008
Beginning ASP.NET 2.0 databases: from novice to professional Authors: Damien Foggon, Pages: 625, Published: 2006
Pro C# 2008 and the .NET 3.5 platform Authors: Andrew Troelsen, Pages: 1370, Published: 2007
Programming Entity Framework Authors: Julia Lerman, Pages: 828, Published: 2009
Asp .Net 2.0 Website Programming Authors: Marco Bellinaso, Pages: 0, Published: -1

Web:
HOW TO: Build a dynamic gridView at runtime in ASP.NET HOW TO: Build a dynamic gridView at runtime. ... The question is how to make gridview at runtime - not design time. ...
HOW TO: Build a dynamic gridView at runtime - ASP.NET Forums Re: HOW TO: Build a dynamic gridView at runtime. 08-23-2006, 5:40 PM. Contact ... Re: HOW TO: Build a dynamic gridView at runtime ...
HOW TO: Build a dynamic gridView at runtime - ASP.NET Forums This is an example on the same line, if you want to give a custom header or formatting to dynamic gridview at run time. ...
How to build and manipulate data in GridView control at runtime in ... I want to create a GridView dynamically at runtime for a shoping cart sample. initially the gridview control will have only one row .
Dynamic Template Columns in the ASP.NET 2.0 GridView Control To make matters even trickier, we didn't know until runtime what the query would ... a GridView up from scratch using a template to respond to a dynamic query; .... Microsoft Partner Portal Video: Microsoft Gold Certified Partners Build ...

Postback in Linkbutton inside Gridview! - asp.net_ajax.asp ... I've tried make a postback in a linkbutton inside a gridview in my web form ... Scott on Writing Given a LinkButton inside a dynamic user ...
Remove the Header from a GridView Control? - general_asp.net ... "If you make it idiot proof, they'll build a better idiot". alexdski. Asp.Net User ... gridview: dynamic templatefield ...
GridView Web Part - Paging Issue - ng.asp-net-forum ... GridView Web Part - Paging Issue, > ROOT > NEWSGROUP > Asp.Net Forum ... Build your own ASP.NET 2.0 web site using C# & VB Authors: Cristian Darie ... Dynamic GridView Paging Issue - NullReferenceException - Windows Live ...
How can I filter my gridview results with a checkbox list? - ng ... Excel's Filter Dialog, My GridView Filter Extender ... subsequent rows for the same column , we will need to build the checkbox list that . ...
Paging and sorting in dynamically created Gridview - ng.asp-net ... How can i create a Gridview dynamically with paging and sorting ... In a previous article I had written on Dynamic Column Sorting and Paging ...






create a gis web application with asp.net

re: best asp.net faq for interviews

formatting text

forms authentication - redirecting users to a page other than default.aspx

asp.net 2.0 dataset etiquette/best practises

insert an apostrophe into a sql string

cultureinfo, currentculture, currentuiculture stuff

preventing validation error messages from disapperaing during postback.

how to thread safe create, read, edit, write xml file (for logging in web application)

stored procedure

error "allowcustompaging must be true and virtualitemcount must be set for a datagrid..."

question:asp crystal report in apache server

how do you get your frickin' web host to install ajax

how to develope accounting software

getting error names "the server {22148139-f1fc-4eb0-b237-dfcd8a38effc} did not register with dcom within the required timeout"

re: smtp server and email faq

web security: input validation in asp.net applications

how do i disable the back button in a web browser?

you may receive the error "parser error message: could not load type 'webapplication1.global'." when browsing an asp.net page

importing csv to sql database

change color of a cell

please use this forum to post faq-type q&as, not to ask general questions!

versioning

custom contols (and design-time) faq

where is the asp.net documentation?

debugging application

single sign on application

where to use abstract and where to use interface???

help needed with backing up outlook email folders and settings

using sql server stored procedure for implementing custom paging

   
  Privacy | Contact Us
All Times Are GMT