Thursday, March 1, 2012

Read DataKeyNames value of Gridview row using Asp.net C#




Please visit my new Web Site https://coderstechzone.com



When we need to bind data in a Gridview column then we need to add an unique reference number which will help to identify a specific object or a datarow. Some developers use hidden field to store the ID column of a table on which he can INSERT UPDATE or DELETE based on hidden ID column. But this is not a good practice. Because Gridview control gives us a property named DataKeyNames on which we can assign our unique ID or code column value to distinguish invidual row. Here in this example i will show how one can read DataKeyNames value from code behind. Asp.net Gridview control also provides us a facility to assign more ID or Code type column in a single Gridview for each DataRow item specialy for composite keys of a table to bind. I have already discuss "How to use more DataKeynames in a Gridview". Also i have discuss on "Jquery to read DatakeyNames value of Selected Rows of GridView".

Sample Output:
Read Datakeynames of a Gridview row

HTML Markup Code:
<asp:GridView ID="GridView1" runat="server" DataKeyNames="ID" HorizontalAlign="Left">
        <Columns>
            <asp:boundfield datafield="Name" headertext="Super Player" />
        </Columns>
    </asp:GridView>

Codebehind Code:
protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            DataTable dtPlayers = new DataTable("Super_Player");
            dtPlayers.Columns.Add(new DataColumn("ID", System.Type.GetType("System.UInt64")));
            dtPlayers.Columns.Add(new DataColumn("Name"));
            dtPlayers.Rows.Add(1, "Leonel Messi");
            dtPlayers.Rows.Add(2, "Christiano Ronaldo");
            dtPlayers.Rows.Add(3, "Carlos Tevez");
            dtPlayers.Rows.Add(4, "Xavi");
            dtPlayers.Rows.Add(5, "Iniesta");
            GridView1.DataSource = dtPlayers;
            GridView1.DataBind();

            foreach (GridViewRow oRow in GridView1.Rows)
                Response.Write("DataKeyNames="+GridView1.DataKeys[oRow.RowIndex].Value + "
");
        }
    }
Hope now you can use DataKeyNames property of a Gridview control efficiently when required.

1 comments:

Anonymous said...

Thank you, this is very helpful.

Want to say something?
I WOULD BE DELIGHTED TO HEAR FROM YOU

Want To Search More?
Google Search on Internet
Subscribe RSS Subscribe RSS
Article Categories
  • Asp.net
  • Gridview
  • Javascript
  • AJAX
  • Sql server
  • XML
  • CSS
  • Free Web Site Templates
  • Free Desktop Wallpapers
  • TopOfBlogs
     
    Free ASP.NET articles,C#.NET,VB.NET tutorials and Examples,Ajax,SQL Server,Javascript,Jquery,XML,GridView Articles and code examples -- by Shawpnendu Bikash