Want to win a PS4? Go Premium and enter to win our High-Tech Treats giveaway. Enter to Win

x
?
Solved

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

Posted on 2013-11-01
9
Medium Priority
?
42,276 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 6
  • 3
9 Comments
 
LVL 41

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 41

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
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 

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 41

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

What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

Question has a verified solution.

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

One of the pain points with developing AJAX, JavaScript, JQuery, and other client-side behaviors is that JavaScript doesn’t allow for cross domain request for pulling content. For example, JavaScript code on www.johnchapman.name could not pull conte…
ASP.Net to Oracle Connectivity Recently I had to develop an ASP.NET application connecting to an Oracle database.As I am doing it first time ,I had to solve several problems. This article will help to such developers  to develop an ASP.NET client…
Have you created a query with information for a calendar? ... and then, abra-cadabra, the calendar is done?! I am going to show you how to make that happen. Visualize your data!  ... really see it To use the code to create a calendar from a q…
This lesson discusses how to use a Mainform + Subforms in Microsoft Access to find and enter data for payments on orders. The sample data comes from a custom shop that builds and sells movable storage structures that are delivered to your property. …
Suggested Courses

604 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