Pages

Tuesday 9 April 2013

Get GridView Cell value using JavaScript

Summary : article about how to get GridView cell value using java script code
Get gridView Column Value using JavaScript
To demonstrate how to get value form GridView cell we need first GridView with filled data inside it. so here i created simple User class holding Three fields ID,Username and Password and bound that list with the GridView and displayed it so here is code for data binding.
public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        User usr = new User();
        GridView1.DataSource = usr.GetUsers();
        GridView1.DataBind();
    }
}
public class User
{
    public int ID { get; set; }
    public string Username { get; set; }
    public string  Password { get; set; }
    public List<User> GetUsers()
    {
        //Return List of Users
        List<User> list = new List<User>()
        {
            new User{ID=1,Username="Person1",Password="12345"},
            new User{ID=2,Username="Person2",Password="45678"},
            new User{ID=3,Username="Person3",Password="90123"},
            new User{ID=4,Username="Person4",Password="4567"},
            new User{ID=5,Username="Person5",Password="88"},
            new User{ID=6,Username="Person6",Password ="11"},
        };
        return list;
    }
}
And here java script code to get Password Column Value and Write it to document.
<script type="text/javascript">
   function GetValues()
    {
        var table = document.getElementById('<%=GridView1.ClientID %>');
        for (var i = 1; i < table.rows.length; i++)
        {
            var Row = table.rows[i];
            var CellValue = Row.cells[2].innerText;
            document.writeln(CellValue);
        }
    }
</script>
<input type="button" value="Get Column Value" onclick='GetValues();' />

No comments:

Post a Comment