Tuesday 17 July 2012

" Use DropDownList in ASP.NET GridView Control."



Default.aspx

<asp:GridView ID="dgCountry" runat="server" CellPadding="4" ForeColor="#333333"
            AutoGenerateColumns="False" DataKeyNames="CountryId"
        GridLines="None" onrowcancelingedit="dgCountry_RowCancelingEdit"
            onrowediting="dgCountry_RowEditing"
            onrowdatabound="dgCountry_RowDataBound" onrowupdating="dgCountry_RowUpdating" >
    <AlternatingRowStyle BackColor="White" />
    <Columns>
        <asp:TemplateField HeaderText="Country Name">
            <EditItemTemplate>
                <%--<asp:TextBox ID="gdTxtName" runat="server" Text='<%# Bind("CountryName") %>'></asp:TextBox>--%>
                <asp:DropDownList ID="ddlSubCategories" runat="server" >                

        </asp:DropDownList>

            </EditItemTemplate>
            <ItemTemplate>
                <asp:Label ID="Label1" runat="server" Text='<%# Bind("CountryName") %>'></asp:Label>
            </ItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="Description">
            <EditItemTemplate>
                <asp:TextBox ID="gdtxtDesc" runat="server" Text='<%# Bind("Description") %>'></asp:TextBox>
            </EditItemTemplate>
            <ItemTemplate>
                <asp:Label ID="Label2" runat="server" Text='<%# Bind("Description") %>'></asp:Label>
            </ItemTemplate>
        </asp:TemplateField>
        <asp:CommandField ShowDeleteButton="True" />
        <asp:CommandField ShowEditButton="True" />
    </Columns>
    <FooterStyle BackColor="#990000" Font-Bold="True" ForeColor="White" />
    <HeaderStyle BackColor="#990000" Font-Bold="True" ForeColor="White" />
    <PagerStyle BackColor="#FFCC66" ForeColor="#333333" HorizontalAlign="Center" />
    <RowStyle BackColor="#FFFBD6" ForeColor="#333333" />
    <SelectedRowStyle BackColor="#FFCC66" Font-Bold="True" ForeColor="Navy" />
    <SortedAscendingCellStyle BackColor="#FDF5AC" />
    <SortedAscendingHeaderStyle BackColor="#4D0000" />
    <SortedDescendingCellStyle BackColor="#FCF6C0" />
    <SortedDescendingHeaderStyle BackColor="#820000" />
    </asp:GridView>


Default.aspx.cs


// *****************Fill Grid View*************************
    public void MFill_Country()
    {
        DataSet ds = new DataSet();
        try
        {
              string connStr = @"Data Source=.\sqlexpress;Initial Catalog=JobOnlinePortal;Integrated Security=True";
              SqlConnection conn = new SqlConnection(connStr);
            SqlCommand cmd = new SqlCommand("FetchRecord",conn);
            cmd.CommandType = CommandType.StoredProcedure;

            SqlDataAdapter da = new SqlDataAdapter(cmd);
            da.Fill(ds);
            dgCountry.DataSource = ds.Tables[0];
            dgCountry.DataBind();
        }
        catch (Exception ex) { throw new Exception(ex.Message); }

     
    }

// *****************Cancel*************************
    protected void dgCountry_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
    {
        dgCountry.EditIndex = -1;
        MFill_Country();
    }

// *****************Edit*************************
    protected void dgCountry_RowEditing(object sender, GridViewEditEventArgs e)
    {
        dgCountry.EditIndex = e.NewEditIndex;
        MFill_Country();
    }

// *****************Method for retrieve data of  Country*************************

    private DataTable RetrieveCountryforFillDropDownGridView()
    {

        //fetch the connection string from web.config

        string connStr = @"Data Source=.\sqlexpress;Initial Catalog=JobOnlinePortal;Integrated Security=True";
     

        //SQL statement to fetch entries from Country

        string sql = @"select CountryId,CountryName from tblCountry";

        DataTable dtSubCategories = new DataTable();

        //Open SQL Connection

        using (SqlConnection conn = new SqlConnection(connStr))
        {

            conn.Open();

            //Initialize command object

            using (SqlCommand cmd = new SqlCommand(sql, conn))
            {

                SqlDataAdapter adapter = new SqlDataAdapter(cmd);

                //Fill the result set

                adapter.Fill(dtSubCategories);

            }

        }

        return dtSubCategories;

    }

// ***************** Country data which Fill DropDown in GridView *************************

    protected void dgCountry_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {

            //check if is in edit mode

            if ((e.Row.RowState & DataControlRowState.Edit) > 0)
            {

                DropDownList ddlSubCategories =

                          (DropDownList)e.Row.FindControl("ddlSubCategories");

                //Bind subcategories data to dropdownlist

                ddlSubCategories.DataTextField = "CountryName";

                ddlSubCategories.DataValueField = "CountryId";

                ddlSubCategories.DataSource =  RetrieveCountryforFillDropDownGridView() ;

                ddlSubCategories.DataBind();


                DataRowView dr = e.Row.DataItem as DataRowView;

                ddlSubCategories.SelectedValue =

                             dr["CountryId"].ToString();

            }

        }

    }



    private void UpdateProduct(int id, string Name, string Description)
{
//fetch the connection string from web.config
string connString = @"Data Source=.\sqlexpress;Initial Catalog=JobOnlinePortal;Integrated Security=True";
//SQL statement to update a product          "select , from ";
using (SqlConnection conn = new SqlConnection(connString))
{
    conn.Open();
    //Initialize command object
    SqlCommand cmd = new SqlCommand("UpdateCountry", conn);
    cmd.CommandType = CommandType.StoredProcedure;
    cmd.Parameters.Add("@id", id);
    cmd.Parameters.Add("@Name", Name);
    cmd.Parameters.Add("@Description", Description);
    cmd.ExecuteNonQuery();
}
    }


//************************ Update Row ****************
    protected void dgCountry_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
        // Get the product id of the selected product    

        string productID = dgCountry.DataKeys[e.RowIndex].Value.ToString();
        int cid = Convert.ToInt32(productID);

        // Get the GridViewRow object that represents the row being edited

        // from the Rows collection of the GridView control.            

        GridViewRow row = dgCountry.Rows[e.RowIndex];



        // Get the controls that contain the updated values. In this

        // example, the updated values are contained in the TextBox

        // controls declared in the edit item templates of each TemplateField

        // column fields in the GridView control.

        DropDownList ddlSubCategories =

                          (DropDownList)row.FindControl("ddlSubCategories");

        TextBox txtCDesc = (TextBox)row.FindControl("gdtxtDesc");

     

        //update the product

        UpdateProduct(cid,ddlSubCategories.SelectedItem.ToString(), txtCDesc.Text);

        dgCountry.EditIndex = -1;

         MFill_Country();

    }






No comments:

Post a Comment