Solved

How to get my gridview column names and cell values in RowDataBound Event

Posted on 2013-11-01
9
39,630 Views
Last Modified: 2014-01-27
I am using C# in  my code behind, with 3.5 environment.  

I have  a gridview with a Select command.  The gridview columns are generated by code, but the columns may change depending on which table is selected.
I have date and date/time fields and need to format them when the gridview is populated so the correct data format shows.

The gridview populates with data, so I know there is data in it.

I built my RowDataBound function, and am trying to loop through the columns to get the data type.  The cell count returned is 5 for what I am testing, which is correct.  However, the column names are blank.  How can I get to the rest of the columns that are in my dataset and get the name of the column and the contents of the row cell?

Here is my html gridview:

<asp:GridView ID="grdvwReview" runat="server" AllowPaging="True" 
        AllowSorting="True" BackColor="White" BorderColor="#CC9966" BorderStyle="None" 
        BorderWidth="1px" CellPadding="4" 
        PageSize="20" style="text-align: left" 
        Width="95%"  OnRowDataBound="grdvwReview_RowDataBound" onpageindexchanging="grdvwReview_PageIndexChanging" 
        onselectedindexchanging="grdvwReview_SelectedIndexChanging" 
        onsorting="grdvwReview_Sorting">
        <RowStyle BackColor="White" ForeColor="#330099" />
        <Columns>
            <asp:CommandField ShowSelectButton="True">
            <ItemStyle Width="50px" />
            </asp:CommandField>
        </Columns>
        <FooterStyle BackColor="#FFFFCC" ForeColor="#330099" />
        <PagerSettings Mode="NumericFirstLast" PageButtonCount="5" Position="TopAndBottom" />
        <PagerStyle BackColor="#FFFFCC" ForeColor="#330099" HorizontalAlign="Left" />
        <SelectedRowStyle BackColor="#FFCC66" Font-Bold="True" ForeColor="#663399" />
        <HeaderStyle BackColor="#990000" Font-Bold="True" ForeColor="#FFFFCC" />
        <AlternatingRowStyle BackColor="#FFFF99" />
    </asp:GridView>

Open in new window


Here is my LoadGrid():

private void LoadGrid()
        {

            
            string strSQL = "";
            strSQL = " SELECT   RecNum, " + GetAllFields() + " " +
                     " FROM     " + txtTableName.Text.Trim() + 
                     " ORDER BY " + (string)Session["ViewOrder"];

                if (strSQL != "")
                {
                    SqlDataAdapter da = new SqlDataAdapter(strSQL, strConnection);
                    DataSet ds = new DataSet();
                    da.Fill(ds);
           
		    grdvwReview.DataSource = ds.Tables[0];
                    
                    grdvwReview.DataBind();

                    if (ds.Tables[0].Rows.Count <= 0)
                    {
                        lblFeedback.Text = "There are no Records to view at this time.";
                    }
		}
}

Open in new window


Here is my RowDataBound function:

protected void grdvwReview_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            // If it is a date or datetime or time, get the format and format the output accordingly - I have this code

            if (e.Row.RowType == DataControlRowType.Header)
            {

                string l_type = "";
                string strt = "";
                string l_format = "";

               for (int i = 0; i < e.Row.Cells.Count; i++)
                {

                        l_type = CheckDataType(e.Row.Cells[i].Text.Trim());

                        if (l_type == "Date")
                        {                        
                            .....
                        }
                        else if (l_type == "Time")
                        {
                           ..... 
                        }
                        else if (l_type == "DateTime")
                        {
		.....
                        }

                    }
                
            }
        }

Open in new window

0
Comment
Question by:ptslv
  • 6
  • 3
9 Comments
 
LVL 39

Expert Comment

by:Kyle Abrahams
ID: 39617338
<link removed - GaryC123>


// ---- GetCellByName ----------------------------------
//
// pass in a GridViewRow and a database column name 
// returns a DataControlFieldCell or null

static public DataControlFieldCell GetCellByName(GridViewRow Row, String CellName)
{
    foreach (DataControlFieldCell Cell in Row.Cells)
    {
        if (Cell.ContainingField.ToString() == CellName)
            return Cell;
    }
    return null;
}

// ---- GetColumnIndexByHeaderText ----------------------------------
//
// pass in a GridView and a Column's Header Text
// returns index of the column if found 
// returns -1 if not found 

static public int GetColumnIndexByHeaderText(GridView aGridView, String ColumnText)
{
    TableCell Cell;
    for (int Index = 0; Index < aGridView.HeaderRow.Cells.Count; Index++)
    {
        Cell = aGridView.HeaderRow.Cells[Index];
        if (Cell.Text.ToString() == ColumnText)
            return Index;
    }
    return -1;
}

// ---- GetColumnIndexByDBName ----------------------------------
//
// pass in a GridView and a database field name
// returns index of the bound column if found 
// returns -1 if not found 

static public int GetColumnIndexByDBName(GridView aGridView, String ColumnText)
{
    System.Web.UI.WebControls.BoundField DataColumn;

    for (int Index = 0; Index < aGridView.Columns.Count; Index++)
    {
        DataColumn = aGridView.Columns[Index] as System.Web.UI.WebControls.BoundField;

        if (DataColumn != null)
        {
            if (DataColumn.DataField == ColumnText)
                return Index;
        }
    }
    return -1;
}

Open in new window

0
 

Author Comment

by:ptslv
ID: 39617461
Am I passing the column name in to the different functions from RowDataBound?
0
 
LVL 39

Expert Comment

by:Kyle Abrahams
ID: 39617779
For GetCellByName you pass in the Row  (eg: e.Row) for the first parameter, and the string name for the 2nd.

The other 2 take the gridview itself and the columntext.
0
 

Author Comment

by:ptslv
ID: 39617890
The problem is I don't know what my column names are.  This is a generic gridview page that is used by many tables.  That is why I need to be able to loop through the columns to find the fields that are DateTime, etc.
0
How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

 

Author Comment

by:ptslv
ID: 39617921
I modified my code in RowDataBound a bit just to see if I could get the column names.  I was able to do that, but now I am having difficulty getting the cell value in the row.  Here is my revised code:

foreach (DataControlFieldCell cell in e.Row.Cells)
                {
                    foreach (Control ctl in cell.Controls)
                    {
                        LinkButton link = ctl as LinkButton;
                        if (link != null)
                        {
                            string columnheader = link.Text;
                        
                            l_type = CheckDataType(columnheader); // this is returning correct data
                        }


                        if (l_type == "Date")
                        {
                            DateTime dt = new DateTime();
                            //dt = Convert.ToDateTime(cell.Text.Substring(0, 10).ToString( 'dd/mm/yyyy'));
                                                      
                         }

Open in new window


I have tried different ways to get the value in the cell.  I have tried to get the substring also, but to no avail.... cell.Text returns "".
0
 
LVL 39

Expert Comment

by:Kyle Abrahams
ID: 39617926
My apologies completely misread the question:


                System.Data.DataTable dt = (DataTable) grdvwReview.DataSource;
                foreach (System.Data.DataColumn c in dt.Columns)
                {
                    c.DataType;  //use this to check against types.
                 }
0
 

Author Comment

by:ptslv
ID: 39656489
I am not having a problem checking against a datatype.  I am getting my data types.  I am having a problem returning the value in the column of the record.  The value is returning a null or blank..
0
 

Accepted Solution

by:
ptslv earned 0 total points
ID: 39801416
I was able to get this working using the following:

if (e.Row.RowType == DataControlRowType.DataRow)
            {
                for (int i = 1; i < e.Row.Cells.Count; i++)
                {
                    BoundField field = (BoundField)((DataControlFieldCell)e.Row.Cells[i]).ContainingField;

                    if (field.HeaderText.Contains("Date"))
                    {
                         .......... do something
                    }
                }
       }

Open in new window

0
 

Author Closing Comment

by:ptslv
ID: 39811518
I was unable to get my code working using the provided options.  In reworking the problem, I was able to find the solution.
0

Featured Post

Better Security Awareness With Threat Intelligence

See how one of the leading financial services organizations uses Recorded Future as part of a holistic threat intelligence program to promote security awareness and proactively and efficiently identify threats.

Join & Write a Comment

IntroductionWhile developing web applications, a single page might contain many regions and each region might contain many number of controls with the capability to perform  postback. Many times you might need to perform some action on an ASP.NET po…
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…
In this seventh video of the Xpdf series, we discuss and demonstrate the PDFfonts utility, which lists all the fonts used in a PDF file. It does this via a command line interface, making it suitable for use in programs, scripts, batch files — any pl…
This tutorial demonstrates a quick way of adding group price to multiple Magento products.

747 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

12 Experts available now in Live!

Get 1:1 Help Now