Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. Web Development
  3. ASP.NET
  4. how to fix datagrid column width/height when AutoGeneratedColumns is ture?

how to fix datagrid column width/height when AutoGeneratedColumns is ture?

Scheduled Pinned Locked Moved ASP.NET
helptutorialquestion
10 Posts 3 Posters 0 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • S Offline
    S Offline
    steven_wong
    wrote on last edited by
    #1

    hello, everyone: I am creating a DataGrid form a DataSet with autogeneratecolumns: dg.DataSource = ds; dg.DataBind(); But I want to change the style of the columns. Particularly speaking, i want to have all the columns have fixed width/height so that the datagrid may look better. It is because some of the content may have many words. I have tried many methods,however, the datagrid never changed.:(( Any ideas? ThanX in advance!

    M 1 Reply Last reply
    0
    • S steven_wong

      hello, everyone: I am creating a DataGrid form a DataSet with autogeneratecolumns: dg.DataSource = ds; dg.DataBind(); But I want to change the style of the columns. Particularly speaking, i want to have all the columns have fixed width/height so that the datagrid may look better. It is because some of the content may have many words. I have tried many methods,however, the datagrid never changed.:(( Any ideas? ThanX in advance!

      M Offline
      M Offline
      Mike Ellison
      wrote on last edited by
      #2

      Yea, this can be tricky when auto-generating the columns, because you don't have direct access to the columns. Here's a hack you can try - it involves trapping the PreRender event for the datagrid (this assumes the data is bound prior to PreRender) and manually inspecting the grid's child control Table. Below is an example of what I mean.

      <%@ Page Language="C#" %>
      <%@ Import Namespace="System.Data" %>

      <script runat="server">

      // upon page load, initialize the list
      void Page\_Load(object o, EventArgs e)
      {
          if (!IsPostBack)
          {
              myList.DataSource = CreateDataSource();
              myList.DataBind();   
              
              myList2.DataSource = CreateDataSource();
              myList2.DataBind();         
          }
      }
      
      
      // Create the sample datasource for this exercise
      private DataTable CreateDataSource()
      {
          DataTable t = new DataTable();
          
          // create the table structure
          DataColumn c = new DataColumn();
          c.DataType = System.Type.GetType("System.Int32");
          c.ColumnName = "ID";
          c.Unique = true;
          t.Columns.Add(c);
          
          c = new DataColumn();
          c.DataType = System.Type.GetType("System.String");
          c.ColumnName = "Name";
          t.Columns.Add(c);        
          
          c = new DataColumn();
          c.DataType = System.Type.GetType("System.String");
          c.ColumnName = "City";
          t.Columns.Add(c);    
          
          // establish ID as the primary key
          DataColumn\[\] primaryKey = new DataColumn\[1\];
          primaryKey\[0\] = t.Columns\["ID"\];
          t.PrimaryKey = primaryKey;
      
          // populate the table with some sample rows of data
          DataRow r = t.NewRow();
          r\["id"\] = 1001; r\["Name"\] = "Jack Bauer"; r\["City"\] = "Los Angeles";
          t.Rows.Add(r);
          
          r = t.NewRow();
          r\["id"\] = 1002; r\["Name"\] = "David Palmer"; r\["City"\] = "Washington D.C.";
          t.Rows.Add(r);
          
          r = t.NewRow();
          r\["id"\] = 1003; r\["Name"\] = "Nina Meyers";
          r\["City"\] = "Los Angeles";  t.Rows.Add(r);
      
          r = t.NewRow();
          r\["id"\] = 1004; r\["Name"\] = "Bill Buchanan";
          r\["City"\] = "Los Angeles";  t.Rows.Add(r);
          
          return t;
      }
      
      
      private void DG\_PreRender(object o, EventArgs e)
      {    
          DataGrid dg = (o as DataGrid);
          if (dg != null)
          {
              Table t = (dg.Controls\[0\] as
      
      M 1 Reply Last reply
      0
      • M Mike Ellison

        Yea, this can be tricky when auto-generating the columns, because you don't have direct access to the columns. Here's a hack you can try - it involves trapping the PreRender event for the datagrid (this assumes the data is bound prior to PreRender) and manually inspecting the grid's child control Table. Below is an example of what I mean.

        <%@ Page Language="C#" %>
        <%@ Import Namespace="System.Data" %>

        <script runat="server">

        // upon page load, initialize the list
        void Page\_Load(object o, EventArgs e)
        {
            if (!IsPostBack)
            {
                myList.DataSource = CreateDataSource();
                myList.DataBind();   
                
                myList2.DataSource = CreateDataSource();
                myList2.DataBind();         
            }
        }
        
        
        // Create the sample datasource for this exercise
        private DataTable CreateDataSource()
        {
            DataTable t = new DataTable();
            
            // create the table structure
            DataColumn c = new DataColumn();
            c.DataType = System.Type.GetType("System.Int32");
            c.ColumnName = "ID";
            c.Unique = true;
            t.Columns.Add(c);
            
            c = new DataColumn();
            c.DataType = System.Type.GetType("System.String");
            c.ColumnName = "Name";
            t.Columns.Add(c);        
            
            c = new DataColumn();
            c.DataType = System.Type.GetType("System.String");
            c.ColumnName = "City";
            t.Columns.Add(c);    
            
            // establish ID as the primary key
            DataColumn\[\] primaryKey = new DataColumn\[1\];
            primaryKey\[0\] = t.Columns\["ID"\];
            t.PrimaryKey = primaryKey;
        
            // populate the table with some sample rows of data
            DataRow r = t.NewRow();
            r\["id"\] = 1001; r\["Name"\] = "Jack Bauer"; r\["City"\] = "Los Angeles";
            t.Rows.Add(r);
            
            r = t.NewRow();
            r\["id"\] = 1002; r\["Name"\] = "David Palmer"; r\["City"\] = "Washington D.C.";
            t.Rows.Add(r);
            
            r = t.NewRow();
            r\["id"\] = 1003; r\["Name"\] = "Nina Meyers";
            r\["City"\] = "Los Angeles";  t.Rows.Add(r);
        
            r = t.NewRow();
            r\["id"\] = 1004; r\["Name"\] = "Bill Buchanan";
            r\["City"\] = "Los Angeles";  t.Rows.Add(r);
            
            return t;
        }
        
        
        private void DG\_PreRender(object o, EventArgs e)
        {    
            DataGrid dg = (o as DataGrid);
            if (dg != null)
            {
                Table t = (dg.Controls\[0\] as
        
        M Offline
        M Offline
        miniThomas
        wrote on last edited by
        #3

        Hello , I tried using your code but the page displayed following error on line 66.. Server Error in '/CodeProject' Application. Specified argument was out of the range of valid values. Parameter name: index Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. Exception Details: System.ArgumentOutOfRangeException: Specified argument was out of the range of valid values. Parameter name: index Source Error: Line 64: if (dg != null) Line 65: { Line 66: Table t = (dg.Controls[0] as Table); Line 67: if (t != null) Line 68: { ..pls can u figure out what the problem is Thanks, Mini

        M 1 Reply Last reply
        0
        • M miniThomas

          Hello , I tried using your code but the page displayed following error on line 66.. Server Error in '/CodeProject' Application. Specified argument was out of the range of valid values. Parameter name: index Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. Exception Details: System.ArgumentOutOfRangeException: Specified argument was out of the range of valid values. Parameter name: index Source Error: Line 64: if (dg != null) Line 65: { Line 66: Table t = (dg.Controls[0] as Table); Line 67: if (t != null) Line 68: { ..pls can u figure out what the problem is Thanks, Mini

          M Offline
          M Offline
          Mike Ellison
          wrote on last edited by
          #4

          Hi Mini. The code worked as is for me... did you change the datasource or when the data is bound? The one thing about the technique I demonstrated is that the data must be bound to the grid before the PreRender (or other event of choice) is triggered. If the data isn't bound, then there isn't a child Table control to inspect, and I'm guessing that's why you're getting an error referencing dg.Controls[0]. Another way to go about this, that is probably better anyway, is to use the ItemDataBound event of the DataGrid. Take a look at the event documentation for it on MSDN and you'll see an example of how it is used. It's very similar to the approach I showed here, except that you'll access a table row and its cells through the event args that are passed to the ItemDataBound event handler, rather than accessing the child Table control directly. If there's interest, I might be able to work up an article on this fairly quickly.

          S 1 Reply Last reply
          0
          • M Mike Ellison

            Hi Mini. The code worked as is for me... did you change the datasource or when the data is bound? The one thing about the technique I demonstrated is that the data must be bound to the grid before the PreRender (or other event of choice) is triggered. If the data isn't bound, then there isn't a child Table control to inspect, and I'm guessing that's why you're getting an error referencing dg.Controls[0]. Another way to go about this, that is probably better anyway, is to use the ItemDataBound event of the DataGrid. Take a look at the event documentation for it on MSDN and you'll see an example of how it is used. It's very similar to the approach I showed here, except that you'll access a table row and its cells through the event args that are passed to the ItemDataBound event handler, rather than accessing the child Table control directly. If there's interest, I might be able to work up an article on this fairly quickly.

            S Offline
            S Offline
            steven_wong
            wrote on last edited by
            #5

            Thank u, Mike and miniThomas, for the attention. I have tried both of the approach, however, the datagrid is still not changed.:(( I am wondering if it is beacause the width of the datagrid could not be longer than certain value, for some of the columns are really quite long. looking forward to ur further answer.:) Regards, Steven

            M 1 Reply Last reply
            0
            • S steven_wong

              Thank u, Mike and miniThomas, for the attention. I have tried both of the approach, however, the datagrid is still not changed.:(( I am wondering if it is beacause the width of the datagrid could not be longer than certain value, for some of the columns are really quite long. looking forward to ur further answer.:) Regards, Steven

              M Offline
              M Offline
              Mike Ellison
              wrote on last edited by
              #6

              Hi Steven. I do think you'll want to trap ItemDataBound in your datagrid. You can Google "ItemDataBound" for examples. I've submitted an article about this topic that will hopefully get posted soon that also shows an example.

              S 1 Reply Last reply
              0
              • M Mike Ellison

                Hi Steven. I do think you'll want to trap ItemDataBound in your datagrid. You can Google "ItemDataBound" for examples. I've submitted an article about this topic that will hopefully get posted soon that also shows an example.

                S Offline
                S Offline
                steven_wong
                wrote on last edited by
                #7

                Thank u for ur reply, looking forward to ur new article.:laugh:

                M M 2 Replies Last reply
                0
                • S steven_wong

                  Thank u for ur reply, looking forward to ur new article.:laugh:

                  M Offline
                  M Offline
                  miniThomas
                  wrote on last edited by
                  #8

                  Hello Mike, Like Steven looking forward to ur article :) Thanks, Mini

                  M 1 Reply Last reply
                  0
                  • S steven_wong

                    Thank u for ur reply, looking forward to ur new article.:laugh:

                    M Offline
                    M Offline
                    Mike Ellison
                    wrote on last edited by
                    #9

                    Posted! http://www.codeproject.com/aspnet/FrmtAutoGenClmnASPNETGrid.asp[^]

                    1 Reply Last reply
                    0
                    • M miniThomas

                      Hello Mike, Like Steven looking forward to ur article :) Thanks, Mini

                      M Offline
                      M Offline
                      Mike Ellison
                      wrote on last edited by
                      #10

                      Posted! http://www.codeproject.com/aspnet/FrmtAutoGenClmnASPNETGrid.asp[^]

                      1 Reply Last reply
                      0
                      Reply
                      • Reply as topic
                      Log in to reply
                      • Oldest to Newest
                      • Newest to Oldest
                      • Most Votes


                      • Login

                      • Don't have an account? Register

                      • Login or register to search.
                      • First post
                        Last post
                      0
                      • Categories
                      • Recent
                      • Tags
                      • Popular
                      • World
                      • Users
                      • Groups