DataKeyNames Property in asp.net

Share it Please
Here I will explain what is DataKeyNames and uses of DataKeyNames with example in asp.net using c# .

Description:-


In previous posts I explained  Value and Reference Types, Asp.net View State, What is the Dataset in ASP.NET,  Difference between .NET Framework 4.5 and .NET Framework 4.0Basics of ASP.NET Now I will explain what is DataKeyNames and uses of DataKeyNames with example in asp.net using c# .

 DataKeyNames Property in asp.net :-

One of the important properties of all the Data presentation controls in ASP.Net is the "DataKeynames" This is available in all of the data controls like GridView, DetailsView....etc. Most of the time we will assign the primary key of the data to this property. We can assign more than one data column value to this field, separated by a comma. This property need to be important at the time of updating a record from the data control. Now we can look one sample on how this datakeyNames were used in a DataGridView.

DataKeyNames in gridview :-

It generally happens with many developers that they want some value from the datasource to be carried in Asp.net Data controls (ListView, GridView etc) but don't want to show that value in the UI.One traditional way to do this is to bind that value to a column or hidden field and set the control  visibility as false. To get rid of that we can use DataKeys and DataKeyNames property of ListView and GridView. The DataKeyNames property is to specify the field names that we want to carry as hidden, from the data source. For more than one field name we use a comma-separated list of field names.

DataKeyNames = 'Field1, Field2, Field3'

When the DataKeyNames property is set, the ListView control automatically creates a DataKey object for each item (GridViewRow, ListViewDataItem) in the control. The DataKey object contains the values of the field or fields that are specified in the DataKeyNames property. Then it is added to the control's DataKeys collection. This provides a convenient way to access different fields of each item.

Objective


The Objective of this program is to show the data from the rows present in Grid View . From This One can Easily Perform the Event and can Fire any Event and do appropriate Task.
This Program shows a row from Grid View by the click of SHOW button. when a user clicks on the button (Event Fired by an User) and therefore corresponding row data is shown . Through DataKeyNames an userid from Grid View is taken at a time and from that we will have to fetch entire row through command text . And  Meanwhile Entire String is passed as a message and shown to User as Output.

.aspx


<html
xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
  <title></title>
  </head>

<body>

    <form id="form1" runat="server">

    <div>

     <table class="style1">

            <tr>

                <td align="center" style="font-family: verdana; font-size: medium; font-weight: bold; font-style: normal; font-variant: normal; text-transform: none; color: #5D7B9D">

                    Displaying Date From Data Key Name</td>
            </tr>
            <tr>
           <td align="left">
         <asp:GridView ID="GridView1" runat="server" Width="60%" DataKeyNames="UserID"
                        AllowPaging="True" PageSize="50" AutoGenerateColumns="False"
                        CellPadding="4" ForeColor="#333333" GridLines="None" >
                        <AlternatingRowStyle BackColor="White" ForeColor="#284775" />
                      <Columns>
                      <asp:BoundField DataField="UserID" HeaderText="UserId" />
          <asp:BoundField DataField="Sponser_id" HeaderText="Sponser Id" />
        <asp:BoundField DataField="UserName" HeaderText="UserName" />
     <asp:BoundField DataField="Mobile" HeaderText="Mobile" />
      <asp:TemplateField HeaderText="Detail Button">
        <ItemTemplate>
        <asp:Button ID="btn_det" runat="server" Text="Show" OnClick="btn_click" />
        </ItemTemplate>
        </asp:TemplateField>                    
         </Columns>
         <EditRowStyle BackColor="#999999" />
           <FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
            <HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
            <PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
               <RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
            <SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
                        <SortedAscendingCellStyle BackColor="#E9E7E2" />
                        <SortedAscendingHeaderStyle BackColor="#506C8C" />
                        <SortedDescendingCellStyle BackColor="#FFFDF8" />
                        <SortedDescendingHeaderStyle BackColor="#6F8DAE" />
                    </asp:GridView>
                </td>
            </tr>
        </table>
   
    </div>
    </form>
</body>
</html>


.CS


using
System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Configuration;
public partial class testing:System.Web.UI.Page
{
  SqlConnection cn = new
SqlConnection(ConfigurationManager.ConnectionStrings["connectionstring"].ConnectionString);
    SqlCommand cmd = new
SqlCommand();
   protected void Page_Load(object sender, EventArgs e)
    {
       this.fill();
    }
    public void fill()
    {
  cn.Open();
 SqlCommand cmd = new
SqlCommand();
 cmd.Connection = cn;
cmd.CommandText = "select id,UserID,Sponser_id,UserName,Mobile from userDetails";
SqlDataAdapter da = new
SqlDataAdapter();
da.SelectCommand = cmd;
  DataTable dt = new DataTable();
 da.Fill(dt);
 cn.Close();
 GridView1.DataSource = dt;
GridView1.DataBind();
    }
    public void
btn_click(object sender, EventArgs e)
    {
        Button btn = (Button)sender;
        GridViewRow gd = (GridViewRow)btn.Parent.Parent;
        string userid =
GridView1.DataKeys[gd.RowIndex].Value.ToString();
 if (btn.Text == "Show")
 {
 cn.Open();
 SqlCommand cmd = cn.CreateCommand();
cmd.CommandText = "select
UserId,Sponser_id,UserName,LoginType,Mobile from UserDetails where
UserId='"+userid+"'";
SqlDataReader dr = cmd.ExecuteReader();
dr.Read();
            string uid = dr["UserId"].ToString();
            string sid = dr["Sponser_id"].ToString();
            string unme = dr["UserName"].ToString();
            string lgnt = dr["LoginType"].ToString();
            string mob = dr["Mobile"].ToString();
           
dr.Close();
cn.Close();
string msg="User Id Is:"+ uid + " Sponser Id Is:"+ sid + " UserName Is :"+ unme + " Login Type Is:" + lgnt+ " Mobile No. is :" + mob;
  string st = "window.alert('"+ msg +"')";
 ScriptManager.RegisterClientScriptBlock(this, this.GetType(),"uniquekey", st,true);    
        }
    }
}

No comments:

Post a Comment

Subscribe via email

Enter your email address:

Delivered by FeedBurner

Blogroll