Click here to Skip to main content
15,885,117 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
As i have tried to use a hidden field in my project.Gridview is binding but its not deleting and updating any record,as hidden filed not finding any value to it.
i have kept id as hidden.

this is my code.
please help me to solve this and also give me easy way to understand how to use hidden field in asp.net.as i am new to ASP.net,i have done this much only.

Thanks in advance.
/////////////////////////////////////////////////////////////////////////////
XML
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="EmployeeDetails.aspx.cs" Inherits="EmployeeDetails" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <style type="text/css">
        .style2
        {
            height: 61px;
        }
    </style>
</head>
<body bgcolor="Aqua" height=100% width=100%>
    <form id="form1" runat="server">
    <div>
    <table border="0" cellpadding="0" cellspacing="0" width="100%">
        <tr>
            <td align="center">
                <table border="0">
                    <tr style="padding-left=100px;padding-right=100px">
                        <td colspan="3">
                            <asp:Label ID="Label1" runat="server" Text="Employee Details " Font-Size="45pt"
                                ForeColor="Maroon"></asp:Label>
                        </td>
                    </tr>
                    <br />
                    <br />

                    <%--<tr>
                        <td align="right" class="style1">
                            <asp:Label ID="Label2" runat="server" Text=" Employee Id" Font-Size="15pt"
                                ForeColor="Maroon"></asp:Label>
                        </td>
                        <td align="left" class="style1">
                            <asp:TextBox ID="txtempid" runat="server" Enabled="False"></asp:TextBox>
                        </td>
                        <td class="style1">

                        </td>
                    </tr>--%>
                    <tr>
                        <td  align="right">
                            <asp:Label ID="Label3" runat="server" Text="Employee Name" Font-Size="15pt"
                                ForeColor="Maroon"></asp:Label>
                        </td>
                        <td align="left">
                            <asp:TextBox ID="txtempname" runat="server"></asp:TextBox>
                        </td>
                        <td align="left">
                            <%--<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server"
                                ErrorMessage="Employee Name can not be a blank" Text="*"
                                ControlToValidate="txtempname" ForeColor="Red"></asp:RequiredFieldValidator>
                            <asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server"
                                ErrorMessage="Name cano not contain numbers and special characters"  Text="*"
                                ControlToValidate="txtempname" ValidationExpression="^[a-z A-Z]{2,25}$"
                                ForeColor="Red"></asp:RegularExpressionValidator>--%>

                        </td>
                    </tr>
                    <tr>
                        <td align="right">
                            <asp:Label ID="Label4" runat="server" Text="Departmetn Name" Font-Size="15pt"
                                ForeColor="Maroon"></asp:Label>
                        </td>
                        <td align="left">
                            <asp:DropDownList ID="drplstdname" runat="server" AutoPostBack="false">
                            <asp:ListItem Value="0">Select</asp:ListItem>
                            </asp:DropDownList>
                        </td>
                        <td align="left">
                            <%--                            <asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server"
                                ErrorMessage="Must select Department Name" InitialValue="0"
                                ControlToValidate="drplstdname" Text="*" ForeColor="Red">*</asp:RequiredFieldValidator>--%>
                        </td>
                    </tr>
                    <tr>
                        <td align="right">
                            <asp:Label ID="Label5" runat="server" Text="Monthly Income" Font-Size="15pt"
                                ForeColor="Maroon"></asp:Label>
                        </td>
                        <td align="left">
                            <asp:TextBox ID="txtsalary" runat="server"></asp:TextBox>
                        </td>
                        <td align="left">
                            <%-- <asp:RegularExpressionValidator ID="RegularExpressionValidator2" runat="server"
                                ErrorMessage="Enter Salary in Numeric Form" Text="*"
                                ControlToValidate="txtsalary" ForeColor="Red"
                                ValidationExpression="^[0-9.]{4,15}$"></asp:RegularExpressionValidator>--%>
                        </td>
                    </tr>
                    <tr>
                        <td align="right">
                            <asp:Label ID="Label6" runat="server" Text="Address" Font-Size="15pt"
                                ForeColor="Maroon"></asp:Label>
                        </td>
                        <td align="left">
                            <asp:TextBox ID="txtaddress" runat="server" TextMode="MultiLine"></asp:TextBox>
                        </td>
                        <td align="left">
                            <%--  <asp:RegularExpressionValidator ID="RegularExpressionValidator3" runat="server"
                                ErrorMessage="Enter proper address" ValidationExpression="^[a-z A-Z 0-9 ,/]{4,15}$"
                                ControlToValidate="txtaddress" ForeColor="Red" Text="*">*</asp:RegularExpressionValidator>--%>
                        </td>
                    </tr>

                    <tr>
                        <td colspan="3">
                            <asp:Button ID="btnadd" runat="server" Text="New" onclick="btnadd_Click" />
                            <asp:Button ID="btndelete" runat="server" Text="Delete"
                                onclick="btndelete_Click" />
                            <asp:Button ID="btnupdate" runat="server" Text="Update"
                                onclick="btnupdate_Click" />

                        </td>

                    </tr>
                    <tr>
                        <td colspan="3" class="style2">
                            <asp:HiddenField ID="hdnempid" runat="server" />
                            <asp:ValidationSummary ID="ValidationSummary1" runat="server" ForeColor="Red" />
                        </td>
                    </tr>
                </table>
            </td>
        </tr>
    </table>
    </div>
    <center>

        <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
            CellPadding="4" ForeColor="#333333" GridLines="None"
            onselectedindexchanged="GridView1_SelectedIndexChanged"
            onrowcommand="GridView1_RowCommand" DataKeyNames="empid">
            <AlternatingRowStyle BackColor="White" />
            <Columns>

                <asp:TemplateField HeaderText="Name">
                    <ItemTemplate>
                        <asp:HiddenField ID=hdnid runat="server" />
                        <asp:LinkButton ID="LinkButton1" runat="server" CommandArgument="empname"
                            CommandName="Show" Text='<%# Eval("empname") %>'></asp:LinkButton>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:BoundField DataField="salary" HeaderText="Salary" />
                <asp:BoundField DataField="address" HeaderText="Address" />
                <asp:BoundField DataField="dname" HeaderText="Department Name" />
            </Columns>
            <EditRowStyle BackColor="#2461BF" />
            <FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
            <HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
            <PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
            <RowStyle BackColor="#EFF3FB" />
            <SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
            <SortedAscendingCellStyle BackColor="#F5F7FB" />
            <SortedAscendingHeaderStyle BackColor="#6D95E1" />
            <SortedDescendingCellStyle BackColor="#E9EBEF" />
            <SortedDescendingHeaderStyle BackColor="#4870BE" />
        </asp:GridView>

    </center>
    </form>
    </body>
</html>


///////////////////////////////////////////////////////////////////////////////
C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;

public partial class EmployeeDetails : System.Web.UI.Page
{
       SqlConnection con;
       SqlCommand cmd;
       SqlDataAdapter da;

    protected void Page_Load(object sender, EventArgs e)
    {
        con = new SqlConnection(@"server=HARSH4-PC\SQLEXPRESS;uid=sa;password=edelcap@1;database=INTERN_DB");
        if (!Page.IsPostBack)
        {

            try
            {
                con.Open();
                cmd = new SqlCommand("EmployeeDetails", con);
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.Parameters.AddWithValue("@flag", SqlDbType.VarChar).Value = "P";
                da = new SqlDataAdapter(cmd);
                DataTable dt = new DataTable();
                da.Fill(dt);
                if (dt.Rows.Count > 0)
                {
                    drplstdname.DataTextField = "dname";
                    drplstdname.DataValueField = "did";
                    drplstdname.DataSource = dt;
                    drplstdname.DataBind();
                   
                }
            }

            catch (Exception ex)
            {
                Response.Write(ex.Message);
            }
            finally
            {
                con.Close();

            }
            BindGrid();

        }
        
    }
    public void BindGrid()
    {
        try
        {
            con.Open();
            cmd = new SqlCommand("EmployeeDetails",con);
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.AddWithValue("@flag", SqlDbType.VarChar).Value = "S";
            da = new SqlDataAdapter(cmd);
            DataSet ds = new DataSet();
            da.Fill(ds, "Employee");
            GridView1.DataSource = ds.Tables[0];
            GridView1.DataBind();
            cmd.ExecuteNonQuery();
        }
        catch (Exception ex)
        {
            Response.Write(ex.Message);
        }
        finally
        {
            con.Close();

        }
    }
    public void CallMyProcedure(string flag)
    {
        try
        {
            con.Open();
            cmd = new SqlCommand("EmployeeDetails", con);
            cmd.CommandType = CommandType.StoredProcedure;
            
            cmd.Parameters.AddWithValue("@flag", SqlDbType.VarChar).Value = flag;
            cmd.Parameters.AddWithValue("@id", SqlDbType.Int).Value = hdnempid.Value.Trim(); 
            cmd.Parameters.AddWithValue("@name", SqlDbType.VarChar).Value = txtempname.Text.Trim();
            cmd.Parameters.AddWithValue("@did", SqlDbType.Int).Value = drplstdname.Text.Trim(); ; 
            cmd.Parameters.AddWithValue("@basic", SqlDbType.Decimal).Value = txtsalary.Text.Trim();
            cmd.Parameters.AddWithValue("@add", SqlDbType.VarChar).Value = txtaddress.Text.Trim();
            cmd.ExecuteNonQuery();
        }
        catch (Exception ex)
        {
            Response.Write(ex.Message);
        }

        finally
        {
            con.Close();
        }
    }
    protected void btnadd_Click(object sender, EventArgs e)
    {
        CallMyProcedure("I");
        BindGrid();
    }
    protected void btndelete_Click(object sender, EventArgs e)
    {
        //RegularExpressionValidator3.Enabled = false;
        //RegularExpressionValidator2.Enabled = false;
        
        CallMyProcedure("D");
        BindGrid();
    }
    protected void btnupdate_Click(object sender, EventArgs e)
    {
        CallMyProcedure("U");
        BindGrid();
    }
    protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
    {
        ////txtempid.Text = GridView1.SelectedRow.Cells[1].Text;
        //txtempname.Text = GridView1.SelectedRow.Cells[1].Text;
        //txtsalary.Text = GridView1.SelectedRow.Cells[2].Text;
        //txtaddress.Text = GridView1.SelectedRow.Cells[3].Text;
        //drplstdname.SelectedItem.Text = GridView1.SelectedRow.Cells[4].Text;
    }


    protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName == "Show")
        {
            GridViewRow row = (GridViewRow)((LinkButton)e.CommandSource).NamingContainer;
           
            hdnempid.Value = ((HiddenField)row.Cells[0].FindControl("hdnid")).Value;
            txtempname.Text = ((LinkButton)row.Cells[0].FindControl("LinkButton1")).Text;
            txtsalary.Text = row.Cells[1].Text;
            txtaddress.Text = row.Cells[2].Text;
            drplstdname.SelectedItem.Text = row.Cells[3].Text;
        }

    }
  
}
Posted
Updated 7-Jan-13 17:35pm
v2

Hi Dear,

Try below code in your gridview hiddenfield.

May Be syntax is not sure. but by this you can know that you have to bind a datatable field to your Hiddenfield which is used in your gridview.


C#
<asp:hiddenfield id="hdnid" runat="server" value="<% #Bind("FieldName") %>" xmlns:asp="#unknown" />


I hope this will helpfull to you.

Thanks
 
Share this answer
 
Comments
Sachin Shinde11088 7-Jan-13 23:38pm    
Mahesh Its Working yaar...
I have tried the way you told.
Sachin Shinde11088 7-Jan-13 23:56pm    
Hey Mahesh Sorry..its Working..
it was my mistake.
after telling u i wrote wrong syntax thats why finding an error.
thank for suggesting me right solution
Mr. Mahesh Patel 8-Jan-13 2:31am    
you welcome Mr. Sachin
Your HiddenField is:
ASP.NET
<asp:hiddenfield id="hdnid" runat="server" />

I think this will give a compile time error. Try changing the above to
ASP.NET
<asp:hiddenfield id="hdnid" runat="server" value='<% #Bind("FieldName") %>'  />

Using this block of code you can find your HiddenField in RowCommand event:
C#
GridViewRow gRow = (GridViewRow) e.CommandSource
HiddenField hdnid= (TextBox)gRow.FindControl("hdnid");



--Amit
 
Share this answer
 
v2
Comments
Sachin Shinde11088 7-Jan-13 23:57pm    
Thanks Amit
_Amy 8-Jan-13 0:00am    
Welcome. :)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900