Solved

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

Posted on 2013-11-01
9
40,592 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 40

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 40

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
Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

 

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
 

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 40

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

Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Problem Hi all,    While many today have fast Internet connection, there are many still who do not, or are connecting through devices with a slower connect, so light web pages and fast load times are still popular.    If your ASP.NET page …
International Data Corporation (IDC) prognosticates that before the current the year gets over disbursing on IT framework products to be sent in cloud environs will be $37.1B.
A short tutorial showing how to set up an email signature in Outlook on the Web (previously known as OWA). For free email signatures designs, visit https://www.mail-signatures.com/articles/signature-templates/?sts=6651 If you want to manage em…

791 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