Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts

DataKeyNames Property in asp.net

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);    
        }
    }
}
Read More

Asp.net ViewState Example in C-Sharp

Here I will explain what is viewstate and uses of viewstate with example in asp.net using c# .

Description:-


In previous posts I explained What is the Dataset in ASP.NET, Difference between .NET Framework 4.5 and .NET Framework 4.0, What is Cloud Computing, Basics of ASP.NET . Now I will explain what is viewstate and uses of viewstate with example in asp.net using c# .


What is ViewState? 


ViewState is used to maintain the state of controls during page postback and if we save any control values or anything in viewstate we can access those values throughout the page whenever it required for that check below simple example.

.aspx 


<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Asp.net ViewState Example in C#, VB.NET</title></head>
<body>
<form id="form1" runat="server">
<div>
<table>
<tr>
<td>ViewState Data:</td><td><b><asp:Label ID="lblViewStateDate" runat="server"/></b></td>
</tr>
<tr><td></td><td> <asp:Button ID="btnClick" runat="server" Text="Get ViewState Data"
onclick="btnClick_Click"/></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.Sql;
using System.Data.SqlClient;
using System.Configuration;
public partial class Test : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            string str = "Welcome to aspdotnetweb4u";
            if (ViewState["SampleText"] == null)
            {
                ViewState["SampleText"] = str;
            }
        }
    }
    protected void btnClick_Click(object sender, EventArgs e)
    {
        lblViewStateDate.Text = ViewState["SampleText"].ToString();
    }
 }

Read More

Difference between .NET Framework 4.5 and .NET Framework 4.0

.NET Framework 4.0 support fallowing features:-

Web.config File Refactoring
Extensible Output Caching
Auto-Start Web Applications
Permanently Redirecting a Page
Shrinking Session State
Expanding the Range of Allowable URLs
Extensible Request Validation
Object Caching and Object Caching Extensibility
Extensible HTML, URL, and HTTP Header Encoding
Performance Monitoring for Individual Applications in a Single Worker Process
Multi-Targeting .... etc

.NET Framework 4.5 support fallowing improvement features:-

Asynchronously Reading and Writing HTTP Requests and Responses
Improvements to HttpRequest handling
Asynchronously flushing a response
Support for await and Task-Based Asynchronous Modules and Handlers

 What is new in .NET Framework 4.5 

.NET Framework 4.5 Support for Windows Runtime
.NET Framework 4.5 Support for Metro Style Applications
.NET Framework 4.5 Support for Async Programming
 Garbage Collector Improvements
.NET Framework 4.5 is Faster ASP.NET Startup
.NET Framework 4.5 Support Better Data Access
.NET Framework 4.5 Support WebSockets                        
 Workflow Support - BCL Support
Read More

Value and Reference Types in c-sharp

Here I will explain what is Value Type v/s Reference Type and uses of  Value Type v/s Reference Type with example in asp.net using c# .

Description:-


In previous posts I explained  Asp.net View State,  What is the Dataset in ASP.NETDifference between .NET Framework 4.5 and .NET Framework 4.0What is Cloud ComputingBasics of ASP.NET . Now I will explain what is Value Type v/s Reference Type and uses of Value Type v/s Reference Type with example in asp.net using c# 

What is Value Type and Reference Type in C#

Unlike some programming languages you might be familiar with, C# has two varieties of data types: value and reference. It's important to know the difference if performance is important to your application, or if you are interested in how C# manages data and memory.

Before diving into the deep sea of C#, I would like to touch the basics of reference and value types.

Reference Types: Always allocated from the managed heap.

Always represented in boxed form.
When we assign a value type to another value type, a field-by-field copy is made.


Value Types: Allocated on thread's stack.

Have two form representations "boxed" and "unboxed"

When we copy a reference type to another reference type, only the memory address is copied.

When a variable is declared using one of the basic, built-in data types or a user defined structure, it is a value type. An exception is the string data type, which is a reference type.
A value type stores its contents in memory allocated on the stack. For example, in this case the value 30 is stored in an area of memory called the stack.

int x = 30;

When the variable x goes out of scope because the method in which it was defined has finished executing, the value is discarded from the stack.
Using the stack is efficient, but the limited lifetime of value types makes them less suited for sharing data between different classes.
In contrast, a reference type, such as an instance of a class or an array, is allocated in a different area of memory called the heap. In the example below, the space required for the ten integers that make up the array is allocated on the heap.

int[] numbers = new int[10];

This memory isn't returned to the heap when a method finishes; it's only reclaimed when C#'s garbage collection system determines it is no longer needed. There is a greater overhead in declaring reference types, but they have the advantage of being accessible from other classes.

Reference types are typically declared using "class" keyword, while the value types are declared by the keyword "struct". Let's see an example of each.

public class ReferenceType
    {
        public int Field { get; set; }
    }
public struct ValueType
    {
        public int Field { get; set; }
    }

Let's now create a console application :-

class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Reference Type");
            ReferenceType referenceType1 = new ReferenceType();
            ReferenceType referenceType2 = new ReferenceType();
            Console.WriteLine(referenceType1.Equals(referenceType2));

            Console.WriteLine("Value Type");
            ValueType valueType1 = new ValueType();
            ValueType valueType2 = new ValueType();
            Console.WriteLine(valueType1.Equals(valueType2));

            Console.ReadLine();
        }
    }

                         
You might have expected that the first Console.WriteLine statement would print "true", but the actual result is "false". System.Object is considered the parent type of all other types and it has the method Equals and implements it in a way that doesn't care about the object's fields, but rather on its reference. However, all value types inherit from System.ValueType, which itself inherit from System.Object. System.ValueType overrides the implementation of Equals with a more logical one that depends on the values of object's fields. 

Let's now have another example and see how reference types are considered equal.

class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Reference Type");
            ReferenceType referenceType1 = new ReferenceType();
            ReferenceType referenceType2 = referenceType1;
            Console.WriteLine(referenceType1.Equals(referenceType2));

            Console.WriteLine("Value Type");
            ValueType valueType1 = new ValueType();
            ValueType valueType2 = valueType1;
            Console.WriteLine(valueType1.Equals(valueType2));

            Console.ReadLine();
        }
    }

Here, both of them print "true". The second Console.WriteLine statement obviously prints true because both objects have the save values for their fields. For the first statement, this explains to us the fact that reference types are used by their reference. In other words, when assigning "referenceType1" to "referenceType2", the CLR only copies referenceType1's reference and assigns it to referenceType2 so both of them become pointing to the same object data in the memory.

Let's summarize and add some other differences between Value Type and Reference Type in the following table. 

 Value Type  Reference Type
 where are they stored in memory ?  Stack  Heap
 Parent Type  System.ValueType  System.Object
 Inheritance  All Value Types are sealed and you can't inherit from other types  You can normally inherit from other types
 Acess modifiers  Protected can not be use  Any Access modifier can be used
Read More

Subscribe via email

Enter your email address:

Delivered by FeedBurner

Blogroll