Solved

width of Columns of ViewGrid in .NET C#

Posted on 2011-02-23
23
924 Views
Last Modified: 2012-06-22
Hi

Well, I have a problem with Widths of Columns of a ViewGrid.

I need that my ViewGrid has enabled "AutoGenerateColumns", this because the DataSource varies by product type. I have this already.

But I need to set the fixed width columns, for example.

When type of product is Vines, I need the width of all columns= 138 px
When type is  juice, the Width of all columns =140 px

How do I do???
Somebody help me
0
Comment
Question by:tenriquez199
  • 10
  • 8
  • 2
23 Comments
 
LVL 76

Expert Comment

by:slightwv (䄆 Netminder)
Comment Utility
I've done something similar with the older datagrid.  You need to loop through columns and set the width dynamically.

I can't find the old datagrid example that gave me the inspiration but found a gridview link.

Check out the GridView1_RowDataBound example in:
http://msdn.microsoft.com/en-us/library/ms178296.aspx

0
 
LVL 1

Author Comment

by:tenriquez199
Comment Utility
Ohmg... I need clear Oracle Database Zone's

and that's it
0
 
LVL 1

Author Comment

by:tenriquez199
Comment Utility
Thanks
0
 
LVL 1

Author Comment

by:tenriquez199
Comment Utility
I do It something like your link
http://msdn.microsoft.com/en-us/library/ms178296.aspx

but i receive this message


Index was out of range. Must be a non-negative and less than the size of the collection.
Parameter name: index

0
 
LVL 14

Expert Comment

by:systan
Comment Utility
Ok; this is different;

for (int i = 0; i < GridView1.Columns.Count   -  1; i++)  //try minus 1
{
GridView1.Columns[i].ItemStyle.Wrap = True;  //SET to TRUE
//If the Wrap property is false, the column is automatically resized.
}

//for product column
GridView1.Columns[0].ItemStyle.Width = 138;
//for other1 column
GridView1.Columns[1].ItemStyle.Width = 140;
//for other2 column
GridView1.Columns[2].ItemStyle.Width = 100;

Open in new window


>>Index was out of range. Must be a non-negative and less than the size of the collection.
Parameter name: index
The index was our of range, maybe because you oversize the index;
eq.,
GridView1.Columns[   2<if you have 3 columns, because it starts on 0 not 1>    ].ItemStyle.Width = 100;
0
 
LVL 1

Author Comment

by:tenriquez199
Comment Utility
I realized that "GridView1.Columns.Count"= 0

So when i go to column 0, dont find it ....
0
 
LVL 14

Expert Comment

by:systan
Comment Utility
Yes, maybe you put the code before the GridView Starts to Load
Put the code snippet after the codes load during startup
eq.,
Page_Load....begin
...
...other codes here that database retrieved to GridView
...
codes here..
...
for (int i = 0; i < GridView1.Columns.Count   -  1; i++)  //try minus 1
{
GridView1.Columns[i].ItemStyle.Wrap = True;  //SET to TRUE
//If the Wrap property is false, the column is automatically resized.
}
...
GridView1.Columns[0].ItemStyle.Width = 138;
...

Open in new window

Page_Load....end
0
 
LVL 76

Expert Comment

by:slightwv (䄆 Netminder)
Comment Utility
I have a little time to mess with this.  Can you post your datagrid declaration?

Also, where is the 'product' stored?  I assume it's outside the datagrid but is it a label, textbox, ???

0
 
LVL 1

Author Comment

by:tenriquez199
Comment Utility
Ok I have a soo big viewgrid with SQL DataSource,

On the DB SQL i have somethin like this....

Type-----Brand--------volume---------amount------date
VINES     California         5                 15000            25/01/11
VINES     California         4                  1120             27/01/11
SODAS   Good4you       12                 890               13/01/11
VINES     St.Ethiene         1                 450               25/01/11


In C# .NET i have next

string type;
string sell; //(SELL IN OTHER PART OF CODE, CAN BE "amount","volume")
if (type.Equals("VINES"))
{

SqlDataSource1.SelectCommand = "SELECT [California], [St.Ethiene], [Total]   FROM (SELECT                                                                                                                                                           .                                               [Brand], [" + sell+ "] FROM [Sicom].[dbo].[jde11$] where Type='VINES'" +
                          " and mes='1') p PIVOT (SUM([" + sell+ "]) FOR [Brand] IN ( [California], [St.Ethiene], "+  .                         "[Total])) AS pvt";
        GridView1.DataBind();
        GridView1.Visible = true;
}

everything works fine....
but when i show it...

the columns move a lot....


WITH STRING TYPE= "VINES"
GRIDVIEW 1-------------------------------------------------------------------------------------------
       Day                          California                                      St.Ethienne                               Total
        25/01/11                    15000                                              450                                        15450
----------------------------------------------------------------------------------------------------------

GRIDVIEW2 --------------------------------------------------------------------------------------------
       Day                                                    California                                          St.Ethienne  Total
         27/01/11                                               1120                                                         0     15450
-----------------------------------------------------------------------------------------------------------

WITH STRING TYPE ="SODAS"

GRIDVIEW2 --------------------------------------------------------------------------------------------
       Day                                                    Good4you                                            Total
         27/01/11                                               890                                                   890              
-----------------------------------------------------------------------------------------------------------


the grids are not aligned, that is why we need to encode the column width depending on the type or some other idea.

the other option I've found is to make a grid for each product, but would take more than 100 grids .... is not feasible
0
 
LVL 76

Expert Comment

by:slightwv (䄆 Netminder)
Comment Utility
>>the other option I've found is to make a grid for each product

The sample you posted looks like you are already using multiple grids:
GRIDVIEW1
...
GRIDVIEW2
...
GRIDVIEW3
...


Please post the aspx code for the page.
0
Do You Know the 4 Main Threat Actor Types?

Do you know the main threat actor types? Most attackers fall into one of four categories, each with their own favored tactics, techniques, and procedures.

 
LVL 1

Author Comment

by:tenriquez199
Comment Utility
<asp:GridView ID="GridView1" runat="server" BackColor="White"
                BorderStyle="None" CssClass="style176" DataSourceID="SqlDataSource37"
                GridLines="Vertical" ShowFooter="True"
                OnRowDataBound="GridView37_RowDataBound" CellSpacing="-1">
                <AlternatingRowStyle BackColor="#F7F7DE" />
                <FooterStyle BackColor="#F7F7DE" />
                <HeaderStyle BackColor="White" Font-Names="Eras Demi ITC" Font-Size="Medium"
                    ForeColor="White" HorizontalAlign="Center" VerticalAlign="Middle" />
            </asp:GridView>
            <asp:GridView ID="GridView2" runat="server" BackColor="White"
                BorderColor="#DEDFDE" BorderStyle="None" BorderWidth="1px" CellPadding="4"
                CssClass="style175" DataSourceID="SqlDataSource36" ForeColor="Black"
                GridLines="Vertical" OnRowDataBound="GridView36_RowDataBound"
                ShowHeaderWhenEmpty="True">
                <AlternatingRowStyle BackColor="White" />
                <FooterStyle BackColor="#CCCC99" />
                <HeaderStyle BackColor="White" Font-Bold="True" Font-Names="Eras Demi ITC"
                    Font-Size="Medium" ForeColor="#00CC66" HorizontalAlign="Center" />
                <PagerStyle BackColor="#F7F7DE" ForeColor="Black" HorizontalAlign="Right" />
                <RowStyle BackColor="#F7F7DE" />
                <SelectedRowStyle BackColor="#CE5D5A" Font-Bold="True" ForeColor="White" />
                <SortedAscendingCellStyle BackColor="#FBFBF2" />
                <SortedAscendingHeaderStyle BackColor="#848384" />
                <SortedDescendingCellStyle BackColor="#EAEAD3" />
                <SortedDescendingHeaderStyle BackColor="#575357" />
            </asp:GridView>
            <asp:GridView ID="GridView3" runat="server" BackColor="White"
                BorderColor="#DEDFDE" BorderStyle="None" BorderWidth="1px" CellPadding="4"
                CssClass="style172" DataSourceID="SqlDataSource33" ForeColor="Black"
                GridLines="Vertical" OnRowDataBound="GridView33_RowDataBound"
                ShowHeaderWhenEmpty="True">
                <AlternatingRowStyle BackColor="White" />
                <FooterStyle BackColor="#CCCC99" />
                <HeaderStyle BackColor="White" Font-Bold="True" Font-Names="Eras Demi ITC"
                    Font-Size="Medium" ForeColor="#00CC66" />
                <PagerStyle BackColor="#F7F7DE" ForeColor="Black" HorizontalAlign="Right" />
                <RowStyle BackColor="#F7F7DE" />
                <SelectedRowStyle BackColor="#CE5D5A" Font-Bold="True" ForeColor="White" />
                <SortedAscendingCellStyle BackColor="#FBFBF2" />
                <SortedAscendingHeaderStyle BackColor="#848384" />
                <SortedDescendingCellStyle BackColor="#EAEAD3" />
                <SortedDescendingHeaderStyle BackColor="#575357" />
0
 
LVL 76

Expert Comment

by:slightwv (䄆 Netminder)
Comment Utility
I'm confused.  You mentioned in http:#a35001245 you didn't want multiple gridviews.  The code you posted confirms you do have multiple gridviews.

Why not just one?
0
 
LVL 1

Author Comment

by:tenriquez199
Comment Utility
Sorry I do not explain well...
Ok Go Again!!...

I have 15 GridView, but the GV's have 15 columns

I dont work only whit a one GV, because I havent make a Query in SQL that get the information that i need...

0
 
LVL 76

Expert Comment

by:slightwv (䄆 Netminder)
Comment Utility
So you are wanting ALL the gridviews on the page to have the same widths?

Why can't you specify the same gridview layout for all of them?  In other words: the same fixed widths hardcoded on the design.



0
 
LVL 1

Author Comment

by:tenriquez199
Comment Utility
Uhmmm Somethin like this...

when type of product is Vines.... the width of ALL GV is 1900 px

whent type is Sodas the Width of ALL GV is 1600 px

and bla bla bla


How I Do these???
""Why can't you specify the same gridview layout for all of them?  In other words: the same fixed widths hardcoded on the design."
0
 
LVL 76

Expert Comment

by:slightwv (䄆 Netminder)
Comment Utility
No.  Why not set all to 1900px if that is the largest one. Do away with the whole 'dynamic' issue.

Even if you don't have the sql set up to return a single result, can you possibly merge the datasets and use a single grid?
0
 
LVL 1

Author Comment

by:tenriquez199
Comment Utility
I did.
But I do not work at all, because the columns do not align
I need fixed columns depending on the type
0
 
LVL 76

Expert Comment

by:slightwv (䄆 Netminder)
Comment Utility
Did you set a fixed size for the columns or just the grid itself?

I'v not done much with gridview but have a lot of datagrid experience.  With datagrids I could set item widths of the individual columns in the grid without doing in code.
0
 
LVL 1

Author Comment

by:tenriquez199
Comment Utility
I need set a fixed size for columns.... the problem its that i've AutoGenerateColumns = true;

Because the columns change depending on the tyoe
0
 
LVL 76

Accepted Solution

by:
slightwv (䄆 Netminder) earned 500 total points
Comment Utility
Sorry for the delay.

Here's the 'news':

From doing the research it appears you cannot access the Columns collection in a gridview autogenerated.

I found a nice workaround on:
http://geekswithblogs.net/michelotti/archive/2006/03/30/73896.aspx

Below is a self-contained page I used for testing.

Hopefully it will provide you enough information.  If not, post back and I'll try to tweak it.
<%@ Page Language="VB" Debug="true" %>

<%@ import namespace = "System.Data" %>

<html>
<title>simple test</title>
<body>

<br/>
<br/>
<script runat="server">

	Function CreateDataSource1() As ICollection
        
        Dim dt As DataTable
        Dim dr As DataRow
        Dim i As Integer

        'create a DataTable
        dt = New DataTable
        dt.Columns.Add(New DataColumn("Day", GetType(String)))
        dt.Columns.Add(New DataColumn("California", GetType(String)))
        dt.Columns.Add(New DataColumn("St.Ethienne", GetType(String)))
        dt.Columns.Add(New DataColumn("Total", GetType(String)))

        dr = dt.NewRow()

        dr(0) = "25/01/11"
        dr(1) = "15000"
        dr(2) = "450"
        dr(3) = "15450"

        dt.Rows.Add(dr)

        CreateDataSource1 = New DataView(dt)
        
    End Function

	Function CreateDataSource2() As ICollection
        
        Dim dt As DataTable
        Dim dr As DataRow
        Dim i As Integer

        'create a DataTable
        dt = New DataTable
        dt.Columns.Add(New DataColumn("Day", GetType(String)))
        dt.Columns.Add(New DataColumn("Good4You", GetType(String)))
        dt.Columns.Add(New DataColumn("Total", GetType(String)))


        dr = dt.NewRow()

        dr(0) = "27/01/11"
        dr(1) = "890"
        dr(2) = "890"

        dt.Rows.Add(dr)

        CreateDataSource2 = New DataView(dt)
        
    End Function


	Sub page_load(sender as object, e as eventargs)
        GridView1.DataSource = CreateDataSource1()
        GridView1.DataBind()

        GridView2.DataSource = CreateDataSource2()
        GridView2.DataBind()

		'from: http://geekswithblogs.net/michelotti/archive/2006/03/30/73896.aspx
		GridView1.Rows(0).Cells(0).Width = Unit.Pixel(200)
		GridView1.Rows(0).Cells(1).Width = Unit.Pixel(200)
		GridView1.Rows(0).Cells(2).Width = Unit.Pixel(200)
		GridView1.Rows(0).Cells(3).Width = Unit.Pixel(200)

		GridView2.Rows(0).Cells(0).Width = Unit.Pixel(200)
		GridView2.Rows(0).Cells(1).Width = Unit.Pixel(400)
		GridView2.Rows(0).Cells(2).Width = Unit.Pixel(200)

	end sub



</script>

<form runat="server">
	<asp:GridView ID="GridView1" runat="server"
				AutoGenerateColumns=true
	/>
	<br/>
	<asp:GridView ID="GridView2" runat="server"
				AutoGenerateColumns=true
	/>

</form>

</body>
</html>

Open in new window

0

Featured Post

Why You Should Analyze Threat Actor TTPs

After years of analyzing threat actor behavior, it’s become clear that at any given time there are specific tactics, techniques, and procedures (TTPs) that are particularly prevalent. By analyzing and understanding these TTPs, you can dramatically enhance your security program.

Join & Write a Comment

Introduction This article shows how to use the open source plupload control to upload multiple images. The images are resized on the client side before uploading and the upload is done in chunks. Background I had to provide a way for user…
Calculating holidays and working days is a function that is often needed yet it is not one found within the Framework. This article presents one approach to building a working-day calculator for use in .NET.
Here's a very brief overview of the methods PRTG Network Monitor (https://www.paessler.com/prtg) offers for monitoring bandwidth, to help you decide which methods you´d like to investigate in more detail.  The methods are covered in more detail in o…
You have products, that come in variants and want to set different prices for them? Watch this micro tutorial that describes how to configure prices for Magento super attributes. Assigning simple products to configurable: We assigned simple products…

763 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

10 Experts available now in Live!

Get 1:1 Help Now