Translate

Friday 20 December 2013

GridView ADD,Delete,Update, paging and Sorting Simple Example

       <table>
            <tr>
                <td align="center">
                    <table>
                        <tr>
                            <td>
                                UserID
                            </td>
                            <td>
                                <asp:TextBox ID="txtUserID" runat="server"></asp:TextBox>
                            </td>
                            <td>
                                UserName
                            </td>
                            <td>
                                <asp:TextBox ID="txtUserName" runat="server"></asp:TextBox>
                            </td>
                            <td>
                                Age
                            </td>
                            <td>
                                <asp:TextBox ID="txtAge" runat="server"></asp:TextBox>
                            </td>
                            <td>
                                <asp:Button ID="btnSubmit" runat="server" Text="Submit" OnClick="btnSubmit_Click" />
                            </td>
                        </tr>
                    </table>
                </td>
            </tr>
            <tr>
                <td align="center">
                    <asp:Panel ID="pnlGrid" runat="server" Width="1008px" Height="550px">
                        <asp:GridView ID="userGrid" runat="server" AutoGenerateColumns="false" AllowPaging="true"
                            AllowSorting="true" PageSize="5" OnRowEditing="userGrid_OnRowEditing" OnRowDeleting="userGrid_OnRowDeleting"
                            OnRowUpdating="userGrid_OnRowUpdating" OnPageIndexChanging="userGrid_PageIndexChanging"
                            OnRowCancelingEdit="userGrid_RowCancelingEdit" DataKeyNames="iUserID,strUserName"
                            EmptyDataText="no record Found" OnSorting="userGrid_sorting">
                            <Columns>
                                <asp:TemplateField HeaderText="S.NO">
                                    <ItemTemplate>
                                        <%# Container.DataItemIndex+1 %>
                                    </ItemTemplate>
                                </asp:TemplateField>
                                <asp:TemplateField HeaderText="UserName" SortExpression="strUserName">
                                    <EditItemTemplate>
                                        <asp:TextBox ID="txtUsername" runat="server" Text='<%#Bind("strUserName") %>'></asp:TextBox>
                                        <asp:RequiredFieldValidator ID="rfvEditusername" ValidationGroup="Edit" runat="server"
                                            SetFocusOnError="true" Display="Dynamic" ControlToValidate="txtUsername" ErrorMessage="Please , Enter User Name."></asp:RequiredFieldValidator>
                                    </EditItemTemplate>
                                    <ItemTemplate>
                                        <asp:Label ID="label1" runat="server" Text='<%#Bind("strUserName") %>'></asp:Label>
                                    </ItemTemplate>
                                </asp:TemplateField>
                                <asp:TemplateField HeaderText="Age" SortExpression="iAge">
                                    <EditItemTemplate>
                                        <asp:TextBox ID="txtAge" runat="server" Text='<%#Bind("iAge") %>'></asp:TextBox>
                                        <asp:RequiredFieldValidator ID="rfvEditAge" ValidationGroup="Edit" runat="server"
                                            SetFocusOnError="true" Display="Dynamic" ControlToValidate="txtAge" ErrorMessage="Please , Enter Age."></asp:RequiredFieldValidator>
                                    </EditItemTemplate>
                                    <ItemTemplate>
                                        <asp:Label ID="label1" runat="server" Text='<%#Bind("iAge") %>'></asp:Label>
                                    </ItemTemplate>
                                </asp:TemplateField>
                                <asp:CommandField ShowEditButton="true" />
                                <asp:CommandField ShowDeleteButton="true" />
                            </Columns>
                            <EmptyDataTemplate>
                                Sorry! Users record was not found.
                            </EmptyDataTemplate>
                        </asp:GridView>
                    </asp:Panel>
                </td>
            </tr>
        </table>

-----------------------------------------------------------------------------------------------------
Using Image icon

 <asp:TemplateField>
                                    <EditItemTemplate>
                                        <asp:ImageButton ID="imgUpdate" ImageUrl="~/Images/edit1.gif" runat="server" CommandName="update"
                                            ToolTip="Update" CausesValidation="true" CommandArgument='<%#Eval("iUserID") %>' />
                                        <asp:ImageButton ID="imgCancel" ImageUrl="~/Images/delete1.png" runat="server" CommandName="Cancel"
                                            ToolTip="Cancel" CausesValidation="true" />
                                    </EditItemTemplate>
                                    <ItemTemplate>
                                        <asp:ImageButton ID="imgEdit" ImageUrl="~/Images/edit.gif" runat="server" CommandName="Edit"
                                            ToolTip="Edit" CausesValidation="true" />
                                        <asp:ImageButton ID="imgDelete" ImageUrl="~/Images/delete.png" runat="server" CommandName="Delete"
                                            ToolTip="Delete" CausesValidation="true" OnClientClick="return confirm('Do you want to delete?')" />
                                    </ItemTemplate>
                                </asp:TemplateField>
------------------------------------------------------------------------------------------------------
GridView with DropDownList

<asp:TemplateField HeaderText="Location">
<ItemTemplate>
<asp:DropDownList ID="ddlCity" runat="server" Width="100px"/>
</ItemTemplate>
</asp:TemplateField>

protected void gvUserInfo_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
conn.Open();
var ddl = (DropDownList)e.Row.FindControl("ddlCity");
int UserID= Convert.ToInt32(e.Row.Cells[3].Text);
SqlCommand cmd = new SqlCommand("select * from State where iUserID=" + UserID, conn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
conn.Close();
ddl.DataSource = ds;
ddl.DataTextField = "StateName";
ddl.DataValueField = "StateID";
ddl.DataBind();
ddl.Items.Insert(0, new ListItem("--Select--""0"));
}
}

------------------------------------------------------------------------------------------------------
using System.Web.Configuration;
using System.Data.SqlClient;
using System.Data;
using System.Data.Common;

string connstring = WebConfigurationManager.ConnectionStrings["Test"].ConnectionString;
    SqlConnection conn;
    protected void Page_Load(object sender, EventArgs e)
    {
        conn = new SqlConnection(connstring);
        if (!IsPostBack)
        {

            BindGrid();
        }
    }

    private void BindGrid()
    {
        SqlCommand cmd = new SqlCommand("DBP_GetUserDetail");
        cmd.Connection = conn;
        cmd.CommandType = CommandType.StoredProcedure;
        SqlDataAdapter da = new SqlDataAdapter(cmd);
        DataTable dt = new DataTable();
        da.Fill(dt);
        DataView DV = dt.DefaultView;

        if (dt.Rows.Count > 0)
        {
            userGrid.DataSource = dt;
            userGrid.DataBind();
            ViewState["DTSource"] = dt;
            if (SortExpression != null)
            {
                DV.Sort = SortExpression + " " + SortDirection;
            }

            userGrid.DataSource = DV;
            userGrid.DataBind();
        }
        else
        {
            userGrid.DataSource = null;
            userGrid.DataBind();
        }

    }
    protected void userGrid_OnRowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        int userID = Convert.ToInt32(userGrid.DataKeys[e.RowIndex].Values["iUserID"]);

        SqlCommand cmd = new SqlCommand("DBP_UpdateUserDetail");
        cmd.Connection = conn;
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.Parameters.AddWithValue("@indication", 2);
        cmd.Parameters.AddWithValue("@iUserId", userID);

        if (conn.State == ConnectionState.Closed)
        {
            conn.Open();
        }
        cmd.ExecuteNonQuery();
        if (conn.State == ConnectionState.Open)
        {
            conn.Close();
        }



        userGrid.EditIndex = -1;
        BindGrid();

    }
    protected void userGrid_OnRowEditing(object sender, GridViewEditEventArgs e)
    {
        userGrid.EditIndex = e.NewEditIndex;
        BindGrid();
    }
    protected void userGrid_OnRowUpdating(object sender, GridViewUpdateEventArgs e)
    {
        int userID = Convert.ToInt32(userGrid.DataKeys[e.RowIndex].Values["iUserID"]);
        string username = Convert.ToString(userGrid.DataKeys[e.RowIndex].Values["strUserName"]);
        TextBox txtname = (TextBox)userGrid.Rows[e.RowIndex].FindControl("txtUsername");
        TextBox txtAge = (TextBox)userGrid.Rows[e.RowIndex].FindControl("txtAge");
        SqlCommand cmd = new SqlCommand("DBP_UpdateUserDetail");
        cmd.Connection = conn;
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.Parameters.AddWithValue("@indication", 1);
        cmd.Parameters.AddWithValue("@iUserId", userID);
        cmd.Parameters.AddWithValue("@strUserName", txtname.Text);
        cmd.Parameters.AddWithValue("@iAge", txtAge.Text);

        if (conn.State == ConnectionState.Closed)
        {
            conn.Open();
        }
        cmd.ExecuteNonQuery();
        if (conn.State == ConnectionState.Open)
        {
            conn.Close();
        }
        userGrid.EditIndex = -1;
        BindGrid();
    }

    protected void userGrid_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        userGrid.PageIndex = e.NewPageIndex;
        BindGrid();
    }
    protected void userGrid_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
    {
        userGrid.EditIndex = -1;
        BindGrid();
    }

    protected void userGrid_sorting(object sender, GridViewSortEventArgs e)
    {
        if (SortExpression != null)
        {
            if (SortExpression == e.SortExpression && SortDirection == "ASC")
                SortDirection = "DESC";
            else
                SortDirection = "ASC";
        }
        SortExpression = e.SortExpression;
        BindGrid();
    }
    private string SortDirection
    {
        get
        {
            if (ViewState["SortDirection"] != null)
                return (String)ViewState["SortDirection"];
            else return "ASC";
        }
        set
        {
            ViewState["SortDirection"] = value;
        }
    }
    private string SortExpression
    {
        get
        {
            if (ViewState["SortExpression"] != null)
                return ViewState["SortExpression"].ToString();
            else return null;
        }
        set
        {
            ViewState["SortExpression"] = value;
        }
    }
    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        SqlCommand cmd = new SqlCommand("DBP_UpdateUserDetail");
        cmd.Connection = conn;
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.Parameters.AddWithValue("@indication", 3);
        cmd.Parameters.AddWithValue("@iUserID", txtUserID.Text);
        cmd.Parameters.AddWithValue("@strUserName", txtUserName.Text);
        cmd.Parameters.AddWithValue("@iAge", txtAge.Text);

        if (conn.State == ConnectionState.Closed)
        {
            conn.Open();
        }
        int result = cmd.ExecuteNonQuery();
        if (conn.State == ConnectionState.Open)
        {
            conn.Close();
        }
        BindGrid();
    }
----------------------------------------------------------------------------------------------

<connectionStrings>  
    <add name="Test" connectionString="Data Source=IP;Initial Catalog=GridTest;User ID=sa;password=sa@123"  providerName="System.Data.SqlClient;"/>

  </connectionStrings>

No comments:

Post a Comment