Question

Using C#/ASP.net how to Change Datagrid column

Asked by: NESupply

How to edit a DataGrid's column(the text or picture) before the DataGrid is drawn?

This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.

Subscribe now for full access to Experts Exchange and get

Instant Access to this Solution

  • Plus...
  • 30 Day FREE access, no risk, no obligation
  • Collaborate with the world's top tech experts
  • Unlimited access to our exclusive solution database
  • Never be left without tech help again

Subscribe Now

Asked On
2006-08-14 at 08:05:24ID21953574
Tags

datagrid

Topics

Miscellaneous Programming

,

Audio Editing

,

Video Editing

Participating Experts
1
Points
500
Comments
9

Trusted by hundreds of thousands everyday for fast, accurate and reliable tech support.

  • "The time we save is the biggest benefit of Experts Exchange to Warner Bros. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange." Mike Kapnisakis, Warner Bros.
  • "Our team likes having a resource that is more secure than just using Google and most experts using this service really know their stuff. It's nice to look here first versus using Google." Dayna Sellner, Lockheed Martin
  • "Anytime that I've been stumped with a problem, 9 out of 10 times Experts Exchange has either the accepted solution or an open discussion of the potential solution to the problem." Kenny Red, eBay Inc.

See what Experts Exchange can do for you.

Got a question?

We've got the answer.

Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.

Screenshot of Experts Exchange Knowledgebase

Need individual assistance?

Our experts are ready to help.

If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.

Screenshot of Experts Exchange Knowledgebase

Want to learn from the best?

Read articles from industry experts.

Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.

Screenshot of an Article

Working on a long term project?

Store your work and research.

Save solutions to your questions, answers you’ve discovered through searching plus helpful articles in your personal knowledgebase for easy future access.

Screenshot of Experts Exchange Knowledgebase

Access the answers to your technology questions today.

Subscribe Now

30-day free trial. Register in 60 seconds.

What Makes Experts Exchange Unique?

Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Trusted by the world's most respected brands.

image of each brand's logo

Faithfully serving IT professionals since 1996.

Experts Exchange Logo

Try it out and discover for yourself.

Subscribe Now

30-day free trial. Register in 60 seconds.

Related Solutions

  1. ASP.NET Datagrid -- validating edits?
    I have a page with a bound datagrid, using button columns and template columns to setup a linkbutton they can click to edit a row, at which point that row displays textboxes to edit instead of the usual label/tablecell display. Anyway, I want to validate these fields, so tha...
  2. Editing Bound Columns in an ASP.NET Datagrid
    Hi, I have a Datagrid in an ASP.NET page. The data grid needs to be able display and edit data from a table in database. However, the table is arbitary - it could have any number of columns. So the columns need to be added at run time. So this is what I did 1) Set auto...

Free Tech Articles

  1. WARNING: 5 Reasons why you should NEVER fix a computer for free.
    It is in our nature to love the puzzle. We are obsessed. The lot of us. We love puzzles. We love the challenge. We thrive on finding the answer. We hate disarray. It bothers us deep in our soul. W...
  2. SCCM OSD Basic troubleshooting
    SCCM 2007 OSD is a fantastic way to deploy operating systems, however, like most things SCCM issues can sometimes be difficult to resolve due to the sheer volume of logs to sift through and the dispe...
  3. Migrate Small Business Server 2003 to Exchange 2010 and Windows 2008 R2
    This guide is intended to provide step by step instructions on how to migrate from Small Business Server 2003 to Windows 2008 R2 with Exchange 2010. For this migration to work you will need the fo...
  4. Create a Win7 Gadget
    This article shows you how to create a simple "Gadget" -- a sort of mini-application supported by Windows 7 and Vista. Gadgets can be dropped anywhere on the desktop to provide instant information, ...
  5. Outlook continually prompting for username and password
    There have been a lot of questions recently regarding Outlook prompting for a username and password whilst using Exchange 2007. There are a few reasons why this would happen and I will try to cover t...
  6. Backup Exchange 2010 Information Store using Windows Backup
    There seems to be quite a lot of confusion around the ability to backup Exchange 2010 using the built in Windows Backup feature. This stems from the omission of this feature prior to Exchange 2007 s...

Cloud Class Webinars

  1. Avoiding Bugs in Microsoft Access
    Alison Balter takes and in-depth look at avoiding bugs in Access. In this webinar you will learn about using the immediate window to debug your applications, invoking the debugger, using breakpoints to troubleshoot, stepping through code, setting the next statement to execute, ...
  2. Top 10 Best New Features in Visio 2010
    Scott Helmers gives live demonstrations of the top 10 new features in Visio 2010. This webinar will teach you how to create compelling diagrams by adding shapes to the page with a single click, linking the shapes in a diagram to data in Excel (or SQL Server, or SharePoint), ...
  3. IT Consultant Business Secrets Revealed
    Michael Munger, Experts Exchange tech pro and IT consultant, pulls back the curtain on his very successful businesses and answers question on every IT consultant and business owner should know about. He shares secrets on what he did to solve the 5 most common problems in IT, ...
  4. Disaster Recovery and Business Continuity
    Quest CTO, Mike Billon, gives an overview of the steps involved in building a dunamic disaster recovery plan. Through case studies and an examination of software/hardware tooles for monitoring and testing, you'll gain a better understandin of where you are, where you want ...
  5. Organize Your Visio Diagrams with Containers and Lists
    Scott Helmers uses cross functional flowcharts, wireframe diagrams, data graphic legends and seating charts to teach you: how to ustilize all three new structured diagram components in Visio 2010, the best practices for organizeing shapes in previous version of Visio, how to organize ...
  6. How to Us Objects, Properties, Events and Methods in Microsoft Access
    Alison Dalter gives an in-depbth look at objects, properties, events and methods in Microsoft Access. In this webinar you will learn about using the object browser, referring to objects, working with properties and methods, working with object variables, understanding the ...

Join the Community

Give a Little. Get a Lot.

Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.

Join the Community

Answers

 

by: HeadspacePosted on 2006-08-14 at 09:00:04ID: 17311175

I must not have covered this well enough in the last question; here's a commented version of the last example.  Let me know where i need to provide more information.

private void DataGrid1_PreRender(object sender, EventArgs e)  //allows manipulation of the datagrid prior to render, but after databinding
{
     foreach (DataGridItem itm in DataGrid1.Items)  //you don't have to iterate here; instead you could select a specific row in the grid.
     {
          Image img = (Image)itm.Cells[cell number that holds the image control].Controls[1];  //gets the control in the specified cell
          if (img.ImageUrl == null)//allows manipulation of the control or its contents
          {
               itm.Cells[cell number that holds the image control].Controls.Clear();n  //allows manipulation of the datagrid row or its contents
          }
     }
}

wil

 

by: NESupplyPosted on 2006-08-15 at 06:16:07ID: 17317316

I am curious about what some of the properties are of the Datagrid. Most of what I read on the datagrid properties is a lot of double talk.
DataGrid1.Items[x]-->represents of a single row?
DataGrid1.Items.cells[x]-->represents a single cell?
DataGrid1.Items.cells[x].Controls--> represents ???? I have no idea. It is an array?

I get an error on ->Image img
c:\inetpub\wwwroot\SurplusInventory\DisplaySelectList.aspx.cs(153): 'Image' is an ambiguous reference

Thanks Tim


 

by: HeadspacePosted on 2006-08-15 at 08:05:22ID: 17318353

1. DataGrid1.Items[x]-->represents of a single row?

yes, or more correctly, a DataGridItem: http://msdn2.microsoft.com/en-us/library/system.web.ui.webcontrols.datagriditem.aspx


2. DataGrid1.Items.cells[x]-->represents a single cell?

yep.


3. DataGrid1.Items.cells[x].Controls--> represents ???? I have no idea. It is an array?

technically, it's a control collection: http://msdn2.microsoft.com/en-us/library/system.web.ui.control.controls.aspx.  You can access it in a similar fashion, however:  DataGrid1.Items[x].Cells[x].Controls[x].  Sometimes finding controls in the datagrid can be a little difficult, but you can always iterate when need be.


4. I get an error on ->Image img
c:\inetpub\wwwroot\SurplusInventory\DisplaySelectList.aspx.cs(153): 'Image' is an ambiguous reference

...sounds like you have another type of Image class declared somewhere, and the compiler doesn't know which type of "Image" the one in question is referring to.  Try using a complete declaration: 'System.Web.UI.WebControls.Image img'.  Also, make sure that you haven't declared the wrong image class somewhere in your code (such as System.Drawing.Image).  If you've created your own image class, you might want to think about renaming it.

wil

 

by: NESupplyPosted on 2006-08-15 at 12:24:40ID: 17320639

My code:
protected void DataGrid1_PreRender(object sender, EventArgs e)
        {
            foreach (DataGridItem itm in ProductDataGrid.Items)
            {
              System.Web.UI.WebControls.Image img = (System.Web.UI.WebControls.Image)itm.Cells[8].Controls[1];
              //  if (img.ImageUrl == null)
              //  {
                   // itm.Cells[8].Controls.Clear();
                 
                    //itm.Cells[8].Controls.Clear();
               // }
            }
        }

The Image img problem is fixed,but i get this error when the page is loading

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:

An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.  

Stack Trace:


[ArgumentOutOfRangeException: Specified argument was out of the range of valid values.
Parameter name: index]
   System.Web.UI.ControlCollection.get_Item(Int32 index) +2057582
   SurplusInventory.DisplaySelectList.DataGrid1_PreRender(Object sender, EventArgs e) +148
   System.Web.UI.Control.OnPreRender(EventArgs e) +2066972
   System.Web.UI.WebControls.BaseDataList.OnPreRender(EventArgs e) +21
   System.Web.UI.Control.PreRenderRecursiveInternal() +77
   System.Web.UI.Control.PreRenderRecursiveInternal() +161
   System.Web.UI.Control.PreRenderRecursiveInternal() +161
   System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +1360

 
Also, in your Image img = (Image)itm.Cells[cell number that holds the image control].Controls[1];  //gets the control in the specified cell
how do you know you want [1] for Controls[1]?

thanks
  tim

 

by: HeadspacePosted on 2006-08-15 at 20:17:58ID: 17323201

well, the error looks like you're asking for a control that isn't there; my guess would be that you're forgetting that indexing starts at 0, not 1, and although there may be 8 columns in the datagrid, the 8th cell is actually at index 7 (not 8):

System.Web.UI.WebControls.Image img = (System.Web.UI.WebControls.Image)itm.Cells[7].Controls[1];

...just a guess of course.  You can find exactly what's happening by placing a breakpoint on the prerender method and stepping through it, if you haven't already.

as for knowing the correct index of controls within cells, any cell that has only one server-side control in it will be at index 1; index 0 is given to the html (in the form of a literalcontrol) prior to the webcontrol in the cell.  Luckily, if you're not sure where the controls lie in the cell, you can always iterate them and simply count the iterations to learn their indexes:

//iterating the first cell in the first row in the datagrid
//set a breakpoint here so you can watch the iteration
foreach (Control ctl in DataGrid1.Items(0).Cells(0).Controls)
{
     //do something here that allows you to see the controls as you debug.
     string sCtlClientId = ctl.ClientId;
}

Scott Mitchell has an article here that can help, too.  Although it deals with template columns, the fundamentals are the same:  http://datawebcontrols.com/faqs/ProgrammaticAccess/AccessingTemplateColumnContents.print.shtml

let me know if you still need help with the error after reading this.
wil

 

by: NESupplyPosted on 2006-08-16 at 05:01:00ID: 17325431

No, i think my index is ok. My datagrid has like 14 columns. About half are visible. TemplateColumn is what i am trying to update with the prerender
my grid:

<asp:DataGrid id="ProductDataGrid" OnPreRender="DataGrid1_PreRender" OnPageIndexChanged="PageChangeClicked" OnItemCommand="DetailsClicked" OnSortCommand="SortEventHandler" style="Z-INDEX: 101; LEFT: 27px; POSITION: absolute; TOP: 66px" runat="server" Width="963px" AllowSorting="True" AllowPaging="True" AutoGenerateColumns="False" Font-Names="Arial Unicode MS" PageSize="15" CellPadding="1" BorderColor="Black" CellSpacing="1">
                <AlternatingItemStyle BackColor="#ccff66"></AlternatingItemStyle>
                <Columns>
                    <asp:BoundColumn DataField="product_id" SortExpression="product_id DESC" HeaderText="Product ID" ItemStyle-Height="10px" HeaderStyle-Height="10px">
                        <HeaderStyle Font-Size="Medium" Font-Underline="True" Font-Names="Book Antiqua" Wrap="False" HorizontalAlign="Center" VerticalAlign="Middle"></HeaderStyle>
                        <ItemStyle HorizontalAlign="Left" VerticalAlign="Middle"></ItemStyle>
                    </asp:BoundColumn>
                    <asp:BoundColumn DataField="line" Visible="False" HeaderText="Line">
                        <HeaderStyle Font-Size="Medium" Font-Underline="True" Font-Names="Book Antiqua" HorizontalAlign="Center" VerticalAlign="Middle"></HeaderStyle>
                    </asp:BoundColumn>
                    <asp:BoundColumn DataField="category" SortExpression="category DESC" HeaderText="Category" ItemStyle-Wrap="False">
                        <HeaderStyle Font-Size="Medium" Font-Underline="True" Font-Names="Book Antiqua" HorizontalAlign="Center" VerticalAlign="Middle"></HeaderStyle>
                        <ItemStyle HorizontalAlign="Left" VerticalAlign="Middle"></ItemStyle>
                    </asp:BoundColumn>
                    <asp:BoundColumn DataField="sub_category" SortExpression="sub_category DESC" HeaderText="Sub-Category">
                        <HeaderStyle Font-Size="Medium" Font-Underline="True" Font-Names="Book Antiqua" Wrap="False" HorizontalAlign="Center" VerticalAlign="Middle"></HeaderStyle>
                        <ItemStyle HorizontalAlign="Left" VerticalAlign="Middle"></ItemStyle>
                    </asp:BoundColumn>
                    <asp:BoundColumn DataField="manufacturer" SortExpression="manufacturer DESC" HeaderText="Manufacturer">
                        <HeaderStyle Font-Size="Medium" Font-Underline="True" Font-Names="Book Antiqua" HorizontalAlign="Center" VerticalAlign="Middle"></HeaderStyle>
                        <ItemStyle HorizontalAlign="Left" VerticalAlign="Middle"></ItemStyle>
                    </asp:BoundColumn>
                    <asp:BoundColumn DataField="alt_code" Visible="False" HeaderText="Alt Code">
                        <HeaderStyle Font-Size="Medium" Font-Underline="True" Font-Names="Book Antiqua" Wrap="False" HorizontalAlign="Center" VerticalAlign="Middle"></HeaderStyle>
                    </asp:BoundColumn>
                    <asp:BoundColumn DataField="description" HeaderText="Description">
                        <HeaderStyle Font-Size="Medium" Font-Underline="True" Font-Names="Book Antiqua" HorizontalAlign="Center" VerticalAlign="Middle"></HeaderStyle>
                        <ItemStyle HorizontalAlign="Left" VerticalAlign="Middle"></ItemStyle>
                    </asp:BoundColumn>
                    <asp:BoundColumn DataField="list_price" SortExpression="list_price DESC" HeaderText="List Price" DataFormatString="{0:N}">
                        <HeaderStyle Font-Size="Medium" Font-Underline="True" Font-Names="Book Antiqua" Wrap="False" HorizontalAlign="Center" VerticalAlign="Middle"></HeaderStyle>
                        <ItemStyle HorizontalAlign="Right" VerticalAlign="Middle"></ItemStyle>
                    </asp:BoundColumn>
                    <asp:BoundColumn DataField="sale_price" SortExpression="sale_price DESC" HeaderText="Sale Price" DataFormatString="{0:N}">
                        <HeaderStyle Font-Size="Medium" Font-Underline="True" Font-Names="Book Antiqua" Wrap="False" HorizontalAlign="Center" VerticalAlign="Middle"></HeaderStyle>
                        <ItemStyle HorizontalAlign="Right" VerticalAlign="Middle"></ItemStyle>
                    </asp:BoundColumn>
                    <asp:BoundColumn DataField="posted_date" Visible="False" HeaderText="Posted Date">
                        <HeaderStyle Font-Size="Medium" Font-Underline="True" Font-Names="Book Antiqua" HorizontalAlign="Center" VerticalAlign="Middle"></HeaderStyle>
                    </asp:BoundColumn>
                    <asp:BoundColumn DataField="comments" HeaderText="Comments">
                        <HeaderStyle Font-Size="Medium" Font-Underline="True" Font-Names="Book Antiqua" HorizontalAlign="Center" VerticalAlign="Middle"></HeaderStyle>
                        <ItemStyle HorizontalAlign="Left" VerticalAlign="Middle"></ItemStyle>
                    </asp:BoundColumn>
                    <asp:BoundColumn DataField="picture_path" Visible="False" HeaderText="Picture Path">
                        <HeaderStyle Font-Size="Medium" Font-Underline="True" Font-Names="Book Antiqua" HorizontalAlign="Center" VerticalAlign="Middle"></HeaderStyle>
                        <ItemStyle Wrap="False"></ItemStyle>
                    </asp:BoundColumn>
                    <asp:BoundColumn DataField="qty" Visible="False" HeaderText="Qty">
                        <HeaderStyle Font-Size="Medium" Font-Underline="True" Font-Names="Book Antiqua" HorizontalAlign="Center" VerticalAlign="Middle"></HeaderStyle>
                    </asp:BoundColumn>
                    <asp:TemplateColumn HeaderText="Photo" ItemStyle-HorizontalAlign="Center" ItemStyle-VerticalAlign="Middle">
                        <ItemTemplate>
                            <img id="CameraImg" src='images/<%# DataBinder.Eval(Container.DataItem,"picture_path","TSCameraSmall.PNG") %>' alt="N/A" />
                        </ItemTemplate>
                    </asp:TemplateColumn>
                    <asp:ButtonColumn Text="Details" ButtonType="PushButton" HeaderText="Product Details" CommandName="Details">
                        <HeaderStyle Font-Size="Medium" Font-Underline="True" Font-Names="Book Antiqua" Wrap="False" HorizontalAlign="Center" VerticalAlign="Middle"></HeaderStyle>
                        <ItemStyle HorizontalAlign="Center" VerticalAlign="Middle"></ItemStyle>
                    </asp:ButtonColumn>
                </Columns>
                <PagerStyle NextPageText="  Next --&gt;" PrevPageText="&lt;-- Prev.  " HorizontalAlign="Center"></PagerStyle>
            </asp:DataGrid>

thanks
  tim

 

by: HeadspacePosted on 2006-08-16 at 09:45:40ID: 17327732

ahhhh....i see what's happening now.

1. whether columns are visible or not, you still have to count them; the databound column at index 8 doesn't have any controls in it, so naturally an error will occur when you try to access a control that isn't there.  The image control is at index 13 (column 14).

2. html image controls and server-side asp image controls are accessed differently.  The asp image control (<asp:image>) will show up in the datagrid as a System.Web.UI.WebControls.Image, but an html image control (<img/>) is a System.Web.UI.LiteralControl...and in this specific case, since the image is databound, it is a System.Web.UI.DataBoundLiteralControl.  So, with that in mind, you'll have to access it at ProductDataGrid.Items[x].Cells[13].Controls[0], rather than at .Controls[1] (since it isn't a server-side control).

hope that clears it up : )
wil

 

by: NESupplyPosted on 2006-08-16 at 12:28:02ID: 17328933

protected void DataGrid1_PreRender(object sender, EventArgs e)
        {
            foreach (DataGridItem itm in ProductDataGrid.Items)
            {
              System.Web.UI.WebControls.Image img = (System.Web.UI.WebControls.Image)itm.Cells[13].Controls[1];
               if (img.ImageUrl == "")
               {  
                 itm.Cells[13].Controls.Clear();
               }
            }
        }

Thanks your code worked. I had to change 'img.ImageUrl == null' to 'img.ImageUrl == ""'. Not sure why in my database the value is <null> if there is no path set. One last thing when I clear() or use visible prop. I lose my grid border if the cell is cleared. Is there away around this or can I set the border back programmatical?

  Thanks Tim

 

by: HeadspacePosted on 2006-08-16 at 13:45:24ID: 17329517

"I had to change 'img.ImageUrl == null' to 'img.ImageUrl == ""'. Not sure why in my database the value is <null> if there is no path set."

...the null value in the database is not the same null value as defined by the C# language; the null value in the database is read as an empty string.  as a side note, you can also use:

img.ImageUrl == string.Empty;


"One last thing when I clear() or use visible prop. I lose my grid border if the cell is cleared."

...weird.  Assuming that you've redefined the image control in the datagrid as an <asp:image>, then your code shouldn't cause the datagrid's border to disappear.  you can turn the border on programmatically using .BorderStyle, .BorderColor, and .BorderWidth...but i think i'd try to find out why it's getting turned off first.  This could be a residual effect of a bigger problem.  When in doubt, set a break point at ProductDataGrid.DataBind(), and step through the rest of the process to see what's going on.

wil

20120131-EE-VQP-002

3 Ways to Join

30-Day Free Trial

The Experts

98% positive feedback on 31,087 answers since March 2000. angeliii is a Microsoft Most Valuable Professional for his work with MS SQL Server & Develoment.

He has also proven his knowledge of Visual Basic Programming, PHP Scripting and Oracle Databases.

The Experts

97% positive feedback on 10,752 answers since July 2000. lrmoore has more than 18 years experience in the networking industry.

The six-time Mircosoft MVPs specialties include firewalls, virtual private networking, and network management.

Testimonials

"...and excellent source for support... Kind of like having your very own IT dept." Electriciansnet

Testimonials

"I was apprehensive at signing up at first. However... it has already made my life as an IT administrator much easier." JaCrews

Testimonials

"WOW! You guys have great, active, and knowledgeable people on here." moore50

Business Clients

Business Clients

In the Press

"If you’ve got a question... Experts Exchange can supply an answer.”

In the Press

"...an invaluable aid for both IT professionals and those who require tech support."

In the Press

"where IT professionals provide quick answers on just about any topic"

Business Account Plans

Loading Advertisement...