1

I am developing a web application where I need Column's name of grid view using javascript. After that, display this column's name on Div.

Please help me out this.

Mukul Varshney
  • 3,131
  • 1
  • 12
  • 19
SANDEEP
  • 1,062
  • 3
  • 14
  • 32

2 Answers2

2

There is no standard way to do so. GridView is nothing but a html table at runtime. So best you can do is to grab this table through javascript and grab its columns.

Suppose, you have declared your gridview like this:

<asp:GridView ID="GridView1" runat="server">
</asp:GridView>

and have bound it at runtime like this:

        DataTable dt= new DataTable();
        db.Columns.Add("Col1");
        db.Columns.Add("Col2");

        db.Rows.Add("one", "two");
        GridView1.DataSource = dt;
        GridView1.DataBind();

then at runtime, a markup like below is generated for your gridView

<table cellspacing="0" rules="all" border="1" id="GridView1" 
       style="border-collapse:collapse;">
     <tr>
         <th scope="col">Col1</th>
         <th scope="col">Col2</th>
     </tr>
     <tr>
        <td>one</td>
        <td>two</td>
    </tr>
</table>

so clearly, columns are the th elements in the GridView table, which you can easily grab through javascript like below:

var table = document.getElementById('GridView1');
var headers = table.getElementsByTagName('th');

for(var i=0;i<headers.length;i++)
{
    alert(headers[i].innerText);
    //or append to some div innerText
}

see this fiddle on how to grab table elements

Manish Mishra
  • 12,163
  • 5
  • 35
  • 59
0

GridView is rendered as HTML table on your page source, hence you can use Jquery to get the , view source and check if its associated with any class and then you can use it as selector, or regular $('table tr th') this post may help you How to get a table cell value using jQuery?

Community
  • 1
  • 1
foo-baar
  • 1,076
  • 3
  • 17
  • 42
  • Hello Vishal Sachdeva, thanks but i don't want jquery i want use only javascript – SANDEEP Jun 13 '13 at 07:37
  • I dont think there is any difference is both of them Jquery is a library developed using JS to help you reduce syntax, nothing more so document.getElementById('ID') is wripped to $('#ID'). – foo-baar Jun 13 '13 at 07:38