Support us .Net Basics C# SQL ASP.NET ADO.NET MVC Slides C# Programs Subscribe Buy DVD

Hidden field in asp.net - Part 34

Suggested Videos
Part 31 - Adrotator control in asp.net
Part 32 - Asp.net calendar control
Part 33 - Asp.net calendar control properties and events

In this video we will learn about HiddenField in asp.net

The HiddenField control is used to store a value that needs to be persisted across posts to the server, but you don't want the control or it's value visible to the user. For example, when editing and updaing an employee record, we don't want the user to see the EmployeeId. So, we will store the EmployeeId in a HiddenField, so that it can then be used on the server to update the correct employees record.

SQL Script
Create Table tblEmployees
(
Id int Primary Key,
Name nvarchar(50),
Gender nvarchar(10),
DeptName nvarchar(10)
)

Insert into tblEmployees values(201, 'Mark', 'Male', 'IT')
Insert into tblEmployees values(202, 'Steve', 'Male', 'Payroll')
Insert into tblEmployees values(203, 'John', 'Male', 'HR')



HTML of the ASPX Page
<asp:HiddenField ID="HiddenField1" runat="server" />
<table>
    <tr>
        <td>Name:</td>
        <td>
            <asp:TextBox ID="txtName" runat="server"></asp:TextBox>
            </td>
    </tr>
    <tr>
        <td>Gender:</td>
        <td>
            <asp:TextBox ID="txtGender" runat="server"></asp:TextBox>
            </td>
    </tr>
    <tr>
        <td>Department:</td>
        <td>
            <asp:TextBox ID="txtDept" runat="server"></asp:TextBox>
            </td>
    </tr>
</table>
<asp:Button ID="Button1" runat="server" Text="Update Employee" 
    onclick="Button1_Click" />&nbsp;
<asp:Button ID="Button2" runat="server" onclick="Button2_Click" 
    Text="Load Employee" />



Code-Behind code:
protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        LoadEmployee();
    }
}

private void LoadEmployee()
{
    string CS = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
    using (SqlConnection con = new SqlConnection(CS))
    {
        string sqlQuery = "Select Id, Name, Gender, DeptName from tblEmployees where Id=202";
        SqlCommand cmd = new SqlCommand(sqlQuery, con);
        con.Open();
        using (SqlDataReader rdr = cmd.ExecuteReader())
        {
            while (rdr.Read())
            {
                txtName.Text = rdr["Name"].ToString();
                txtGender.Text = rdr["Gender"].ToString();
                txtDept.Text = rdr["DeptName"].ToString();
                HiddenField1.Value = rdr["Id"].ToString();
            }
        }
    }
}

protected void Button1_Click(object sender, EventArgs e)
{
    string CS = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
    using (SqlConnection con = new SqlConnection(CS))
    {
        string sqlQuery = "Update tblEmployees set Name=@Name, Gender=@Gender, DeptName=@DeptName where Id=@Id";
        SqlCommand cmd = new SqlCommand(sqlQuery, con);
                
        cmd.Parameters.AddWithValue("@Name", txtName.Text);
        cmd.Parameters.AddWithValue("@Gender", txtGender.Text);
        cmd.Parameters.AddWithValue("@DeptName", txtDept.Text);
        cmd.Parameters.AddWithValue("@Id", HiddenField1.Value);
        con.Open();
        cmd.ExecuteNonQuery();
        con.Close();

        txtName.Text = "";
        txtDept.Text = "";
        txtGender.Text = "";
    }
}

protected void Button2_Click(object sender, EventArgs e)
{
    LoadEmployee();
}

HiddenField:
1. Value property of the HiddenFiled is used to Get or set the value. 
2. The value is stored as string
3. ViewState uses HiddenFiled to maintain state across postback
4. HiddenField is rendered as an <input type= "hidden"/> element

Alternatives for HiddenField:
View state, QueryStrings, session state, and cookies can be used as an alternative for HiddenField. Session state and cookies will be accessible from other pages as well, and will be available untill their timeout has reached. Where as ViewState and HiddenField data, is available only on that page and the data is lost when you navigate away from the page. 

Advantages of HiddenField:
HiddenFiled data is lost when you navigate away from the page. Doesn't require any explicit cleanup task.
HiddenField is accessible to client-side scripts
<script type="text/javascript">
    function GetHiddenFieldValue() 
    {
        alert(document.getElementById('HiddenField1').value);
    }
</script>

Disadvantage of HiddenField:
Hidden field data can be seen, by viewing the page source. Never, use HiddenFiled to store confidential data

No comments:

Post a Comment

If you like this website, please share with your friends on facebook and Google+ and recommend us on google using the g+1 button on the top right hand corner.