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.
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.
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
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?