Asp.Net

Tuesday, 3 September 2013

Nested Gridview

aspx. cs page

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

public partial class nestedgridview : System.Web.UI.Page
{
    SqlConnection con = new SqlConnection("Data Source=.;Integrated Security=true;Initial Catalog=master");

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            BindGridview();
        }
    }
    // This method is used to bind gridview from database
    protected void BindGridview()
    {
        con.Open();
        SqlCommand cmd = new SqlCommand("select TOP 4 countryid,countryname from country", con);
        SqlDataAdapter da = new SqlDataAdapter(cmd);
        DataSet ds = new DataSet();
        da.Fill(ds);
        con.Close();
        gvParentGrid.DataSource = ds;
        gvParentGrid.DataBind();

    }
    protected void gvUserInfo_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            con.Open();
            GridView gv = (GridView)e.Row.FindControl("gvChildGrid");
            int countryid = Convert.ToInt32(e.Row.Cells[1].Text);
            SqlCommand cmd = new SqlCommand("select * from state where countryid="+ countryid, con);
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            DataSet ds = new DataSet();
            da.Fill(ds);
            con.Close();
            gv.DataSource = ds;
            gv.DataBind();
        }
    }
}

No comments:

Post a Comment