locked
HOW TO: Build a dynamic gridView at runtime RRS feed

  • Question

  • User-1932904831 posted

    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!

     

    Wednesday, August 23, 2006 3:33 PM

All replies

  • User587672878 posted

    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.

    Wednesday, August 23, 2006 5:40 PM
  • User-1932904831 posted
    When you say why not just pass the gridView a dataset do you mean in the design view?  
    Wednesday, August 23, 2006 7:51 PM
  • User-1932904831 posted

    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.

    Thursday, August 24, 2006 9:32 AM
  • User587672878 posted

    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.

    Thursday, August 24, 2006 12:51 PM
  • User1439985827 posted
    That is interesting, but how well does it keep up with things liked editing, adding, and deleting rows?
    Thursday, August 24, 2006 1:45 PM
  • User-1932904831 posted
    I'm not sure what you mean by basic gridView and Strategy-Factory Patterns could you expain a little further?
    Thursday, August 24, 2006 4:43 PM
  • User-1932904831 posted

    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. 

    Thursday, August 24, 2006 4:45 PM
  • User-158764254 posted

    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.

    Thursday, August 24, 2006 7:52 PM
  • User-1932904831 posted
    Completely forgot about that... That is a much easier way. Thanks for your input!
    Friday, August 25, 2006 9:18 AM
  • User-1932904831 posted

    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.

    Friday, August 25, 2006 9:56 AM
  • User-839259635 posted
    Great peice of code, How would I make these col editable? ie text box...
    Tuesday, September 19, 2006 10:33 AM
  • User-1932904831 posted

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

    Tuesday, September 19, 2006 11:17 AM
  • User-158764254 posted

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

    it's built-in...

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

    Tuesday, September 19, 2006 7:03 PM
  • User-36755300 posted

    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.

    Monday, January 22, 2007 1:18 AM
  • User-264353060 posted

    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.net/post/2007/02/07/Dynamic-Gridview-Generation-at-run-time.aspx

     

     

    Sunday, February 11, 2007 11:51 PM
  • Monday, February 12, 2007 1:12 AM
  • User604424641 posted

    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.

    Thursday, March 8, 2007 4:55 PM
  • User142287017 posted

    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, 

     

    Thursday, May 17, 2007 7:36 AM
  • User-1547717038 posted

    Sorry its working

    Friday, May 18, 2007 6:32 AM
  • User279715031 posted
    This is good, however, what if I want to use a different select query? I will have a different data key and that is causing me problems. I fake it out by naming the key with the the same name as the original data grid (in this example it is CustomerID) and it works, or if I create a key for every select query with the same name such as MyKey (replacing CustomerID) and that works. any better suggestions? The problem I run into is when the query has a multi-column key (CutomerID, OrderID, PaymentID). I am looking to tap your smarts. Thanks for your help.<?xml:namespace prefix = o ns = "urn:schemas-microsoft-com:office:office" /><o:p></o:p>
    Friday, June 15, 2007 3:38 PM
  • User769254547 posted

    i used the link above and managed to generate a gridview dynamically with no problems. However....

    i now need to take it a step further and add edit,update,delete funcions to it. Any ideas how?

    Friday, August 24, 2007 8:21 AM
  • User-2102218418 posted

    Thanx for the Link "C#SharpSean"

    was looking for C# code .......

    It helped me to create a datagrid dynamically

    Need to know - how to add edit functions

    thanx

     

    Tuesday, January 15, 2008 11:36 AM
  • User-1263466499 posted

    I am a novice of ASP.NET.Can you please explain in which context dynamic creation of GridView will be useful. 

    Saturday, February 23, 2008 1:31 AM
  • User-839259635 posted

    In my case i am running quality data for pass fail/yields rates for different processes my users requested to have each process have its own "grid"

    depending on which month I do not know how many grids i will need , Jan 4 processes, Feb 2 process March 6 .....

    so I run my query to find out what operations were used for the time frame they selected , then I loop through and create a grid for each operation and fill with data.

    335ICT
    Customer Part No. Passed Failed Total Yield
    ABB 2101059-001 10 0 10 100.00%
    ABB 2101059-002 1 0 1 100.00%
    SIEMS 2020939-001 26 1 27 96.30%
    SIEMS 2020963-002 3 0 3 100.00%
    SLOGX 16-0013SUB 2 0 2 100.00%
    SLOGX 16-0015 3 1 4 75.00%
    Total 45 2 47 95.74%
    BOARD-QC
    Customer Part No. Passed Failed Total Yield
    ABB 2018546-004 10 0 10 100.00%
    Total 10 0 10 100.00%
    FT
    Customer Part No. Passed Failed Total Yield
    ABB 2015636-004 5 0 5 100.00%
    ABB 2018546-004 48 15 63 76.19%
    ASML 4022.471.96242 19 1 20 95.00%
    ASML 4022.471.96302 40 0 40 100.00%
    BRAUN 435178 4 1 5 80.00%
    CYMER 7X10 SERIES CY102116-SUB 3 0 3 100.00%
    CYMER IP CY134210-SUB 3 0 3 100.00%
    CYMER IP CY139255-SUB 3 1 4 75.00%
    CYMER IP CY140904-SUB 3 0 3 100.00%
    CYMER IP CY141555-SUB 13 1 14 92.86%
    CYMER IP CY142677 14 0 14 100.00%
    SIEMS 2015821-001 1 0 1 100.00%
    SIEMS 2020939-001 28 2 30 93.33%
    SIEMS 2020963-002 4 2 6 66.67%
    SLOGX 16-0013SUB 4 0 4 100.00%
    SLOGX 16-0014 1 0 1 100.00%
    Total 193 23 216 89.35%
    SMT-BOTTOM
    Customer Part No. Passed Failed Total Yield
    ABB 2101946-001 28 2 30 93.33%
    ABB 2102080-001 29 1 30 96.67%
    ABB 2102919-001 220 0 220 100.00%
    CYMER IP CY139029 9 0 9 100.00%
    CYMER IP CY141458-SUB 20 0 20 100.00%
    INPUT OUTPUT CIO1448750001 2 0 2 100.00%
    OYOAM 456-02440-07PRO 30 0 30 100.00%
    Total 338 3 341 99.12%
    WAVE
    Customer Part No. Passed Failed Total Yield
    ABB 2012541-002 24 0 24 100.00%
    ABB 2015619-001 20 0 20 100.00%
    ABB 2015636-004 18 0 18 100.00%
    ABB 2017222-004 16 0 16 100.00%
    ABB 2101059-001 5 0 5 100.00%
    ASML 4022.471.96242 20 0 20 100.00%
    CYMER 6X10 SERIES CY06-19166-00 13 1 14 92.86%
    CYMER IP CY123760 12 0 12 100.00%
    CYMER IP CY139029 21 6 27 77.78%
    CYMER IP CY142677 1 0 1 100.00%
    L3 POWER PARAGON 1005109300 0 3 3 0.0000%
    LTX 865-3263-00-SUB 45 0 45 100.00%
    SLOGX 16-0015 1 0 1 100.00%
    THERMA-WAVE 14-017697-SUB 11 0 11 100.00%
    THERMA-WAVE 14-028346-SUB 10 0 10 100.00%
    Total 217 10 227 95.59%
    5DX
    Customer Part No. Passed Failed Total Yield
    CYMER IP CY139029 25 2 27 92.59%
    CYMER IP CY141458-SUB 1 0 1 100.00%
    CYMER IP CY142677 1 0 1 100.00%
    OYOAM 456-02440-07PRO 15 0 15 100.00%
    SIEMS 2020963-002 2 0 2 100.00%
    Total 44 2 46 95.65%
    FINAL QC
    Customer Part No. Passed Failed Total Yield
    ABB 2015619-001 20 0 20 100.00%
    ABB 2015636-004 5 0 5 100.00%
    ABB 2018546-004 50 0 50 100.00%
    ABB 2100299-001 95 0 95 100.00%
    ABB 2101059-001 40 0 40 100.00%
    ABB 2101059-002 80 0 80 100.00%
    ABB 2101946-001 27 0 27 100.00%
    ABB 2102080-001 26 4 30 86.67%
    ASML 4022.471.96242 20 0 20 100.00%
    ASML 4022.471.96302 40 0 40 100.00%
    BRAUN 435178 8 0 8 100.00%
    BRAUN 435245 2 0 2 100.00%
    CYMER IP CY110367 19 0 19 100.00%
    CYMER IP CY110603-SUB 2 0 2 100.00%
    CYMER IP CY112652-SUB 32 0 32 100.00%
    CYMER IP CY142677 14 0 14 100.00%
    HOME 53A01-1 4 0 4 100.00%
    INPUT OUTPUT CIO1448750001 794 0 794 100.00%
    L3 POWER PARAGON 1005109000 3 0 3 100.00%
    L3 POWER PARAGON 1005109300 6 1 7 85.71%
    L3 POWER PARAGON 1005109600 1 1 2 50.00%
    L3 POWER PARAGON 1005109601 6 0 6 100.00%
    L3 POWER PARAGON 1005114700 1 0 1 100.00%
    L3 POWER PARAGON 1005140511 3 0 3 100.00%
    LTX 865-3263-00-SUB 45 0 45 100.00%
    OYOAM 456-02440-07PRO 5 0 5 100.00%
    SIEMS 2015821-001 1 1 2 50.00%
    SIEMS 2020939-001 29 1 30 96.67%
    SIEMS 20209

    Wednesday, February 27, 2008 8:57 AM
  • User421099563 posted

    Hello to Everyone,

    I hope that i can help with this piece of code..

    there are few prerequests in order for it to work

    1.BLL layer with basic clases that will enable us to change them dynamically in the objectDataSource

     2. Gridwiew with basic paging enabled

    3. empty ODS it is important that the ODS is empty because we are going to set its properties dynamically from the codebehind and the gridview.

    Create a GridView and customize the columns by your demands, at this stage do not set the datasource.

    The datasource should be an ObjectDataSource, and should be empty.

    After the markUp is complete, add an GridView1_Load event handler

     What the code does is the following

    1.Set the datasource properties by adding typename, check session, if session is null set initial selectMethod

    2. if session exists, get the session variables and their values and set the datasource with those properties the properties are going to be set and handled between postbacks

    protected void GridView1_Load(object sender, EventArgs e)

    //obj is my name of the datasource

    {

    SearchBLL srch = new SearchBLL(); // init the bll class

    obj.TypeName = "SearchBLL";//set the typename of the datasource

    if (Session.Count == 0)//check if session exists

    {

    //if not set the default select method

    obj.SelectMethod = "Get_TOP25_PUBLISHERS";

    //set the datasource of the GV

    GridView1.DataSource = obj;

    int counter;

    counter = srch.Get_TOP25_PUBLISHERS().Rows.Count;//this is a rowcount for the info label

    Label1.Text = counter.ToString();

    GridView1.DataBind();

    }

    else

    //if any session exists execute this code

    //switch the select method with the session variables chosen from the GridView_RowCommand event handler

    {

    obj.SelectMethod = Session[
    "sM"].ToString();

    obj.SelectParameters.Clear();

    obj.SelectParameters.Add(Session[
    "sC"].ToString(), Session["sN"].ToString());

    GridView1.DataSource = obj;

    GridView1.DataBind();

    }

    }

    //GV row command code

    protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)

    {

    SearchBLL srch = new SearchBLL();// init bll class

     

    if (e.CommandName.Equals("LAST_N"))//check command name

    {

    //IMPORTANT

    // set session variables for the command

    //this code pastes the session variables values to GridView1_Load event handler in order to rebind to the fresh data

    string name = e.CommandArgument.ToString();

    Session["sC"] = "LAST_N";

    Session["sM"] = "Get_COMPLETE_BY_LASTNAME";

    Session["sN"] = name;

    // set the obj datasource required parameters

    obj.SelectMethod = "Get_COMPLETE_BY_LASTNAME"; //This is the name of the BLL sub class and it ties the select query through the bll, this is why we need bll

    obj.SelectParameters.Clear();// clear the existing params

    obj.SelectParameters.Add("LAST_N", name);// add the select param and assign value

    //create a new eventhandler for the paging in order refresh pager GridView1.PageIndexChanging += new GridViewPageEventHandler(GridView1_PageIndexChanging);

    Label1.Text = srch.Get_COMPLETE_BY_LASTNAME(name).Rows.Count.ToString();//count the rows from the new query

    GridView1.PageIndex = 0;//reset pageindex to firstpage

    GridView1.DataBind();

    //bind data

    }

    //BELOW I CHECK COMMAND NAMES AND I EXECUTE THE SAME CODE AS ABOVE BUT WITH DIFFERENT SELECT METHODS THAT GET PASSED

    //TO THE OBJ DATASOURCE

    if (e.CommandName.Equals("SUBJECT"))

    {

    int name = Convert.ToInt32(e.CommandArgument.ToString());

    Session["sC"] = "SUBJECT";

    Session["sM"] = "Get_COMPLETE_BY_SUBJECT";

    Session["sN"] = name;

    obj.SelectMethod = "Get_COMPLETE_BY_SUBJECT";

    obj.SelectParameters.Clear();

    obj.SelectParameters.Add(
    "SUBJECT", name.ToString()); GridView1.PageIndexChanging += new GridViewPageEventHandler(GridView1_PageIndexChanging);

    Label1.Text = srch.Get_COMPLETE_BY_SUBJECT(name).Rows.Count.ToString();//Vraka broj na rekordi za odredeno kveri

    GridView1.PageIndex = 0;//resetira pageindex ili po egzekucija go vraka pagerot na 1va strana

    GridView1.DataBind();

    }

    if (e.CommandName.Equals("DECOR"))

    {

    int name = Convert.ToInt32(e.CommandArgument.ToString());

    Session["sC"] = "DECOR";

    Session["sM"] = "Get_COMPLETE_BY_DECOR";

    Session["sN"] = name;

    obj.SelectMethod = ("Get_COMPLETE_BY_DECOR");

    obj.SelectParameters.Clear();

    obj.SelectParameters.Add(
    "DECOR", name.ToString()); GridView1.PageIndexChanging += new GridViewPageEventHandler(GridView1_PageIndexChanging);

    Label1.Text = srch.Get_COMPLETE_BY_DECOR(name).Rows.Count.ToString();//Vraka broj na rekordi za odredeno kveri

    GridView1.PageIndex = 0;//resetira pageindex ili po egzekucija go vraka pagerot na 1va strana

    GridView1.DataBind();

    }

    if (e.CommandName.Equals("GENRE"))

    {

    int name = Convert.ToInt32(e.CommandArgument.ToString());

    Session["sC"] = "GENRE";

    Session["sM"] = "Get_COMPLETE_BY_GENRE";

    Session["sN"] = name;

    obj.SelectMethod = "Get_COMPLETE_BY_GENRE";

    obj.SelectParameters.Clear();

    obj.SelectParameters.Add(
    "GENRE", name.ToString()); GridView1.PageIndexChanging += new GridViewPageEventHandler(GridView1_PageIndexChanging);

    Label1.Text = srch.Get_COMPLETE_BY_GENRE(name).Rows.Count.ToString();//Vraka broj na rekordi za odredeno kveri

    GridView1.PageIndex = 0;//resetira pageindex ili po egzekucija go vraka pagerot na 1va strana

    GridView1.DataBind();

    }

    }

    //This is the eventhandler for paging, required in order to have a refreshed pager

    protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)

    {

    GridView1.PageIndex = e.NewPageIndex;

    GridView1.DataBind();

    }

    here is the markUp

    <form id="form1" runat="server">

    Total Items: <asp:Label ID="Label1" runat="server" Text="#"></asp:Label>

    <br />

    Items Per Page&nbsp;&nbsp;<asp:TextBox ID="TextBox1" runat="server"
    Width="31px">5</asp:TextBox>&nbsp;

    <asp:Button ID="Button2"

    runat="server" Text="Change" onclick="Button2_Click" />

    &nbsp;&nbsp;&nbsp;&nbsp;Go To Page: <asp:TextBox ID="TextBox2" runat="server"

    Width="31px"></asp:TextBox>

    &nbsp;<asp:Button ID="Button1" runat="server" onclick="Button1_Click"

    Text="GO" />

    &nbsp;&nbsp;&nbsp;&nbsp;

    <asp:Label ID="Label2" runat="server" ForeColor="Red" Visible="False"></asp:Label>

    <br /><br />

    <asp:GridView ID="GridView1" runat="server" OnLoad="GridView1_Load"

    AllowPaging="True" AutoGenerateColumns="False" PageSize="5" Width="100%" onpageindexchanging="GridView1_PageIndexChanging"

    onrowcommand="GridView1_RowCommand" style="text-align: left">

    <PagerSettings Position="TopAndBottom" />

    <Columns>

    <asp:TemplateField HeaderText="Image">

    <ItemTemplate>

    <asp:Image ID="img" runat="server" Width="100" ImageUrl='<%# "~/Posters/" + Eval("PUBLISHER")+"/"+ Eval("NUMBER")+".jpg" %>' />

    </ItemTemplate>

    <ItemStyle HorizontalAlign="Center" VerticalAlign="Middle" />

    </asp:TemplateField>

    <asp:TemplateField HeaderText="Description">

    <ItemTemplate>

    <asp:Label ID="lblTitle" runat="server" Text='<%# Eval("PROPER_TITLE") %>'></asp:Label>

    &nbsp;by

    <asp:LinkButton ID="btnArtist" runat="server" Text='<%# Eval("PROPER_LAST") %>' CommandName="LAST_N"

    CommandArgument='<%# Eval("PROPER_LAST") %>'></asp:LinkButton>

    <br />

    Item#:

    <asp:Label ID="lblItemNum" runat="server" Text='<%# Eval("NUMBER") %>'></asp:Label>

    <br />

    Image Size:

    <asp:Label ID="lblImgWidth" runat="server" Text='<%# Eval("IMGWIDTH") %>'></asp:Label>

    &nbsp;x

    <asp:Label ID="lblImgHeight" runat="server" Text='<%# Eval("IMGHEIGHT") %>'></asp:Label>

    <br />

    Paper Size:

    <asp:Label ID="lblPprWidth" runat="server" Text='<%# Eval("PPRWIDTH") %>'></asp:Label>

    &nbsp;x

    <asp:Label ID="lblPprHeight" runat="server" Text='<%# Eval("PPRHEIGHT") %>'></asp:Label>

    </ItemTemplate>

    </asp:TemplateField>

    <asp:TemplateField HeaderText="Search">

    <ItemTemplate>

    Similar Items By Category:<br />

    <asp:LinkButton ID="btnCatSubject" runat="server" Text='<%# Eval("SubjectDESCRIPTION") %>'

    CommandName="SUBJECT" CommandArgument='<%# Eval("CAT_SUBJECT") %>'></asp:LinkButton>

    <br />

    <asp:LinkButton ID="btnCatDecor" runat="server" Text='<%#Eval("DecorDESCRIPTION") %>'

    CommandName="DECOR" CommandArgument='<%#Eval("CAT_DECOR") %>'></asp:LinkButton>

    <br />

    <asp:LinkButton ID="btnCatGenre" runat="server" Text='<%#Eval("StyleDESCRIPTION") %>'

    CommandName="GENRE" CommandArgument='<%#Eval("CAT_STYLE_GENRE") %>'></asp:LinkButton>

    </ItemTemplate>

    </asp:TemplateField>

    </Columns>

    </asp:GridView>

    <asp:ObjectDataSource ID="obj" runat="server" EnableCaching="True"></asp:ObjectDataSource>

    </form>

    This method wont work if you want to have 3,4,5...10 datasources and change them dynamically

    so the best thing to do is write a basic bll logic like this

     

    1    public class SearchBLL
    2    {
    3        //COMPLETE 24 TABLE
    4        private CompleteTable24TableAdapter _CompleteTableAdapter = null;
    5        protected CompleteTable24TableAdapter completeTableAdapter
    6        {
    7            get
    8            {
    9                if (_CompleteTableAdapter == null)
    10               {
    11                   _CompleteTableAdapter = new CompleteTable24TableAdapter();
    12               }
    13               return _CompleteTableAdapter;
    14           }
    15   
    16   
    17       }
    18       [System.ComponentModel.DataObjectMethodAttribute(System.ComponentModel.DataObjectMethodType.Select, true)]
    19       public SearchDataSet.CompleteTable24DataTable Get_COMPLETE()
    20       {
    21           return completeTableAdapter.Get_COMPLETE();
    22       }
    23   
    24       [System.ComponentModel.DataObjectMethodAttribute(System.ComponentModel.DataObjectMethodType.Select, false)]
    25       public SearchDataSet.CompleteTable24DataTable Get_COMPLETE_BY_DECOR(int DECOR)
    26       {
    27           return completeTableAdapter.Get_COMPLETE_BY_DECOR(DECOR);
    28       }
    29   
    30       [System.ComponentModel.DataObjectMethodAttribute(System.ComponentModel.DataObjectMethodType.Select, false)]
    31       public SearchDataSet.CompleteTable24DataTable Get_COMPLETE_BY_SUBJECT(int SUBJECT)
    32       {
    33           return completeTableAdapter.Get_COMPLETE_BY_SUBJECT(SUBJECT);
    34       }
    35   
    36       [System.ComponentModel.DataObjectMethodAttribute(System.ComponentModel.DataObjectMethodType.Select, false)]
    37       public SearchDataSet.CompleteTable24DataTable Get_COMPLETE_BY_GENRE(int GENRE)
    38       {
    39           return completeTableAdapter.Get_COMPLETE_BY_GENRE(GENRE);
    40       }
    41   
    42       [System.ComponentModel.DataObjectMethodAttribute(System.ComponentModel.DataObjectMethodType.Select, false)]
    43       public SearchDataSet.CompleteTable24DataTable Get_COMPLETE_BY_PUBLISHER(string PUBLISHER)
    44       {
    45           return completeTableAdapter.Get_COMPLETE_BY_PUBLISHER(PUBLISHER);
    46       }
    47   
    48       [System.ComponentModel.DataObjectMethodAttribute(System.ComponentModel.DataObjectMethodType.Select, false)]
    49       public SearchDataSet.CompleteTable24DataTable Get_COMPLETE_BY_LASTNAME(string LAST_N)
    50       {
    51           return completeTableAdapter.Get_COMPLETE_BY_LASTNAME(LAST_N);
    52       }
    53   
    54       [System.ComponentModel.DataObjectMethodAttribute(System.ComponentModel.DataObjectMethodType.Select, true)]
    55       public SearchDataSet.CompleteTable24DataTable Get_TOP25_PUBLISHERS()
    56       {
    57            return completeTableAdapter.Get_TOP25_PUBLISHERS();
    58       }
    59   
    60       [System.ComponentModel.DataObjectMethodAttribute(System.ComponentModel.DataObjectMethodType.Select, false)]
    61       public SearchDataSet.CompleteTable24DataTable Get_COMPLETE_TOP6_BY_VENDOR(string PUBLISHER)
    62       {
    63           return completeTableAdapter.Get_COMPLETE_TOP6_BY_VENDOR(PUBLISHER);
    64       }
    
     
    Monday, March 3, 2008 7:16 PM
  • User1943968726 posted

    Hi all,

    The problem that I see on all the solutions posted is that you have to go through all the code and reinvent the weel I said that because the HTML definition of a grid view is explicit enough to

    being able to hold that definition on an extermal file (XML maybe) read it and use that definition to create any control at runtime.

    So my idea is to create a control that read the control definition and create it at runtime. (that allowed me to change the content of any control at runtime without the need of recompiling

    Something like:


     Partial Class MasterPages_CiGrid
        Inherits System.Web.UI.UserControl

         Public Overrides Sub RenderControl(ByVal writer As System.Web.UI.HtmlTextWriter)

           ' Supposing that the contents of the s variable comes from an external file with the definition of any control
            Dim s As String
            s = "<asp:GridView ID='GridView2' runat='server' DataSourceID='MetricInstvalue' AutoGenerateColumns ='true'> " & _
            "</asp:GridView>" & _
            "<asp:ObjectDataSource ID='MetricInstvalue' runat='server'  " & _
                "SelectMethod='SelectAllReader' " & _
                "TypeName='DataObjects.DataAccess.METRIC_INSTANCE_VALUE'>" & _
            "</asp:ObjectDataSource>"
            writer.Write(s)
            MyBase.RenderControl(writer)
        End Sub


    End Class

     

    But I am affraid that it doesn't work!!!!! any ideas why?????? 

    Friday, March 7, 2008 12:28 PM
  • User-108527277 posted

     

    Hi,

    Do you know how to concatenate multiple datafields from access database and put them in column in gridview[header text]?

    I have addr1, addr2, city, state, zip fields in database. I need to populate them as Address in one column in grid view. I am able to do it using an select statement but I have other fields comming from the database which has to be hyperlinked. So I need to try doing them dynamically somehow to get it.

    Code used is C# and any input will very much appreciated. 

     

    Monday, February 2, 2009 7:55 AM
  • User141931780 posted

    First of all, thanks for the example. It is awsome. I habe a problem however, which I am unable to understand. When I run the code, the gridview generates a second set of the exact same columns. I have included a picture of the outcome. The code is the exact same code as the original post (changing the variables). Any help will be greatly appreciated.

    Regards, Ariel

    GridView

    Thursday, November 26, 2009 9:26 AM
  • User1864465085 posted

    thanks 

    can you please tell me if we want to show all users in membership provider what should we do?

     

    i know we have to get all users from it with

    Dim Users As MembershipUserCollection = Membership.GetAllUsers()


     

    if we have GridView1 in our page and the GridView1.AutoGenerateColumns = False

    and we want to add 2 BoundField to show UserName and Email what sould we do?

    Sunday, December 6, 2009 5:47 PM