Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 42802
  • Last Modified:

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

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
ptslv
Asked:
ptslv
  • 6
  • 3
1 Solution
 
Kyle AbrahamsSenior .Net DeveloperCommented:
<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
 
ptslvAuthor Commented:
Am I passing the column name in to the different functions from RowDataBound?
0
 
Kyle AbrahamsSenior .Net DeveloperCommented:
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
Technology Partners: 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!

 
ptslvAuthor Commented:
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
 
ptslvAuthor Commented:
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
 
Kyle AbrahamsSenior .Net DeveloperCommented:
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
 
ptslvAuthor Commented:
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
 
ptslvAuthor Commented:
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
 
ptslvAuthor Commented:
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: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

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

  • 6
  • 3
Tackle projects and never again get stuck behind a technical roadblock.
Join Now