Wednesday, July 25, 2012

GridView data to DataTable in ASP.Net


   In my project I needed this work and I think it is useful in many cases.
 
    Step-1:
       we have to create a table equal to grigview column we want to get
      public DataTable CreateTable()
        {
            dt = new DataTable();
            dt.Columns.Add("Category", typeof(string));
            dt.Columns.Add("DINPANCINFCRN_No", typeof(string));
            dt.Columns.Add("PromotorsName", typeof(string));
            dt.Columns.Add("FatherOrHusbandName", typeof(string));
            ...........................................up to any column
            dt.Columns.Add("Email", typeof(string)); 
            return dt;

        } 

 
Step-2:     
     Then we have to assign value from Gridview to DataTable

      public DataTable InnerData()
        {
            CreateTable();
            DataRow dr;
            foreach (GridViewRow row in GvPrmoter.Rows)
            {
                dr = dt.NewRow();
                dr[0] = row.Cells[0].Text;
                dr[1] = row.Cells[1].Text;
                dr[2] = row.Cells[2].Text;
                dr[3] = row.Cells[3].Text;
               .....................
                dr[n] = row.Cells[n].Text;
                dt.Rows.Add(dr);
            }          
            return dt;
        }

Step-3:     
     Then we can call the  InnerData() method  inside any event
 

No comments:

Post a Comment