Pages

Tuesday 21 August 2012

How to Edit and Update record of a GridView in Asp.Net?

            In this example, I am describing you how to update Rows of a gridview in Asp.Net. Here I have taken a gridview showing an Employee's Details.
Step-1: Add a page to your solution.
Step-2: Place a gridview inside the page.
Step-3: Modify the gridview and add following templates to your gridview.
My Gridivew after adding templates:
Source Code:

<asp:GridView ID="grdEmployee" runat="server" AutoGenerateColumns="False" ShowHeaderWhenEmpty="true">
            <Columns>
                <asp:TemplateField>
                    <HeaderTemplate>
                        EMPLOYEE NAME</HeaderTemplate>
                    <ItemTemplate>
                        <asp:Label ID="lblName" runat="server" Text='<%#Bind("EmpName") %>'></asp:Label>
                    </ItemTemplate>
                    <EditItemTemplate>
                        <asp:TextBox ID="txtName" runat="server" Text='<%#Bind("EmpName") %>'></asp:TextBox></EditItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField>
                    <HeaderTemplate>
                        GENDER</HeaderTemplate>
                    <ItemTemplate>
                        <asp:Label ID="lblGender" runat="server" Text='<%#Bind("Gender") %>'></asp:Label>
                    </ItemTemplate>
                    <EditItemTemplate>
                        <asp:TextBox ID="txtGender" runat="server" Text='<%#Bind("Gender") %>'></asp:TextBox></EditItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField>
                    <HeaderTemplate>
                        ADDRESS</HeaderTemplate>
                    <ItemTemplate>
                        <asp:Label ID="lblAddress" runat="server" Text='<%#Bind("EmpAddress") %>'></asp:Label>
                    </ItemTemplate>
                    <EditItemTemplate>
                        <asp:TextBox ID="txtAddress" runat="server" Text='<%#Bind("EmpAddress") %>'></asp:TextBox></EditItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField>
                    <HeaderTemplate>
                        IS ACTIVE</HeaderTemplate>
                    <ItemTemplate>
                        <asp:Label ID="lblIsActive" runat="server" Text='<%#Bind("IsActive") %>'></asp:Label>
                    </ItemTemplate>
                    <EditItemTemplate>
                        <asp:TextBox ID="txtActive" runat="server" Text='<%#Bind("IsActive") %>'></asp:TextBox></EditItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField>
                    <HeaderTemplate>
                        EDIT</HeaderTemplate>
                    <ItemTemplate>
                        <asp:LinkButton ID="lnkEdit" runat="server" CausesValidation="false" CommandArgument='<%#Eval("SlNo") %>'
                            CommandName="EditDetails" Text="Edit"></asp:LinkButton></ItemTemplate>
                    <EditItemTemplate>
                        <asp:LinkButton ID="lnkUpdate" runat="server" CausesValidation="false" CommandArgument='<%#Eval("SlNo") %>'
                            CommandName="UpdateDetails" Text="Update"></asp:LinkButton>
                        <asp:LinkButton ID="lnkCancel" runat="server" CausesValidation="false" CommandArgument='<%#Eval("SlNo") %>'
                            CommandName="CancelDetails" Text="Cancel"></asp:LinkButton>
                    </EditItemTemplate>
                </asp:TemplateField>
            </Columns>
        </asp:GridView>
Design View: 

Step-4: After that, create a table in database("Employee" in my case) which will store details of all employees. 

Step-5: Insert some default values into the table.


Step-6: Write a method to fill the grid with employee details and call the method on Page_Load.
SqlConnection con = new SqlConnection(“-----Your Connection String-----“);
    SqlCommand com;
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            FillGrid();
        }
    }

    public void FillGrid()
    {
        com = new SqlCommand("select * from Employee", con);
        DataTable dt = new DataTable();
        SqlDataAdapter da = new SqlDataAdapter(com);
        da.Fill(dt);
        GridView1.DataSource = dt;
        GridView1.DataBind();
    }

The gridview will show the details as following after debugging the page. 
Step-7: Now, write these following lines in the gridview's RowCommand for Updating record.
protected void grdEmployee_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        GridViewRow grd = ((LinkButton)e.CommandSource).Parent.Parent as GridViewRow;
        //******* For Edit the Gridview Row ********//
        if (e.CommandName == "EditDetails")
        {
            grdEmployee.EditIndex = grd.RowIndex;
            FillGrid();
        }
        //******************************************//

        //******* For Row Cancel Editing the Gridview Row ********//
        else if (e.CommandName == "CancelDetails")
        {
            grdEmployee.EditIndex = -1;
            FillGrid();
        }
        //******************************************//

        //******* For Row Updating ********//
        else if (e.CommandName == "UpdateDetails")
        {
            TextBox txtName = (TextBox)grd.FindControl("txtName");
            TextBox txtGender = (TextBox)grd.FindControl("txtGender");
            TextBox txtAddress = (TextBox)grd.FindControl("txtAddress");
            TextBox txtActive = (TextBox)grd.FindControl("txtActive");
            com = new SqlCommand("update Employee set EmpName=@EmpName,Gender=@Gender,EmpAddress=@EmpAddress,IsActive=@IsActive where SlNo=@SlNo", con);
            com.Parameters.AddWithValue("@EmpName", txtName.Text);
            com.Parameters.AddWithValue("@Gender", txtGender.Text);
            com.Parameters.AddWithValue("@EmpAddress", txtAddress.Text);
            com.Parameters.AddWithValue("@IsActive", txtActive.Text);
            com.Parameters.AddWithValue("@SlNo", int.Parse(e.CommandArgument.ToString()));
            con.Open();
            com.ExecuteNonQuery();
            con.Close();
            grdEmployee.EditIndex = -1;
            FillGrid();
        }
        //******************************************//
    }

Output-1(When "Edit" Button is clicked): 

Output-2(When "Cancel" Button is clicked): 

Output-3(After Entering new values): 
Here, I have changed Employee Name of the first row from "Prajanuranjan" to "Prajanuranjan Maharana".

Output-4(When "Update" Button is clicked): 
Value of the gridviewrow will be updated in the database as well as gridview will be reloaded with the new values.
   The updated Database :

   The updated Gridview:




Regards,
Prajanuranjan....


How to maintain Text of a Password field which vanishes after postback in Asp.Net?

       In some situations, if you are having a Password Field in a page, then its text will vanish after each postback  occurred in the page. So, in those situation there are two ways to maintain its text after postback in Asp.Net.
       In the following Example, I have taken two TextBoxes(One for User ID and other one for Password). Then I have a DropDownList from where a User can select his user type and I have set its "AutoPostBack" property to "true".
Procedure-1 : (Using UpdatePanel)
1. Create a .aspx page.
2. Add two TextBoxes(One for UserID and another for Password), One DropDownList and a Button for Login.
3. Set the "TextMode" property of the TextBox meant for Password to "Password".
4. Set the "AutoPostBack" property of the DropDownList to "true".
5. Add an UpdatePanel and place the DropDownList inside its ContentTemplate.

<asp:ScriptManager ID="ScriptManager1" runat="server">
        </asp:ScriptManager>
        <table class="style1">
            <tr>
                <td class="style2">
                    User ID :
                </td>
                <td>
                    <asp:TextBox ID="txtUserID" runat="server"></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td class="style2">
                    Password :
                </td>
                <td>
                    <asp:TextBox ID="txtPassword" runat="server" TextMode="Password"> 
                                                       </asp:TextBox>
                </td>
            </tr>
            <tr>
                <td class="style2">
                    User Type :
                </td>
                <td>
                    <asp:UpdatePanel ID="UpdatePanel1" runat="server">
                        <ContentTemplate>
                            <asp:DropDownList ID="ddlUserType" runat="server" 
                                                                  AutoPostBack="true">
                                <asp:ListItem>Administrator </asp:ListItem>
                                <asp:ListItem>General Employee</asp:ListItem>
                                <asp:ListItem>Visitor</asp:ListItem>
                            </asp:DropDownList>
                        </ContentTemplate>
                    </asp:UpdatePanel>
                </td>
            </tr>
            <tr>
                <td class="style2">
                </td>
                <td>
                    <asp:Button ID="btnLogin" runat="server" Text="Log In" />
                </td>
            </tr>
        </table>
Now, that's it. Now the Password will not vanish after postback.
Procedure-2 : (Without using UpdatePanel)
1. Create a .aspx page.
2. Add two TextBoxes(One for UserID and another for Password), One DropDownList and a Button for Login.
3. Set the "TextMode" property of the TextBox meant for Password to "Password".
4. Set the "AutoPostBack" property of the DropDownList to "true".
<table>
       <tr>
            <td>
                 User ID :
            </td>
             <td>
                 <asp:TextBox ID="txtUserID" runat="server"></asp:TextBox>
            </td>
       </tr>
       <tr>
            <td>
                 Password :
            </td>
            <td>
             <asp:TextBox ID="txtPassword" runat="server" TextMode="Password"></asp:TextBox>
           </td>
      </tr>
      <tr>
           <td>
               User Type :
           </td>
           <td>
               <asp:DropDownList ID="ddlUserType" runat="server" AutoPostBack="true">
                   <asp:ListItem>Administrator </asp:ListItem>
                   <asp:ListItem>General Employee</asp:ListItem>
                   <asp:ListItem>Visitor</asp:ListItem>
               </asp:DropDownList>
          </td>
      </tr>
      <tr>
          <td>
          </td>
          <td>
                <asp:Button ID="btnLogin" runat="server" Text="Log In" />
          </td>
     </tr>
</table>
5. Then, go the code behind and write the following line in the Page_Load Event.
protected void Page_Load(object sender, EventArgs e)
{
    txtPassword.Attributes.Add("value", txtPassword.Text);
}




Regards,
Prajanuranjan....

Total Pageviews