Wednesday, October 19, 2011

How to Copy some rows from a GridView to another in ASP.NET

A junior developer asked me can I select some rows from a GridView and copy them to another GridView?
I told him sure all you have to do is to create a DataTable and the columns that will be added to it.
Now you will loop for each row in the first GridView then add the selected rows to the DataTable.
Set the DataSource of the other GirdView to DataTable.
Here is the code that would do the trick:

DataTable dt = new DataTable();
DataRow dr;
       
dt.Columns.Add(new DataColumn("FirstName"));
dt.Columns.Add(new DataColumn("LastName"));
      
foreach (GridViewRow row in GridViewEmployees.Rows)
 {            
  if(((CheckBox)row.Cells[3].FindControl("CheckBox")).Checked == true)
   {
    dr = dt.NewRow();
    dr["ColumnName1"] = ((Label)row.Cells[0].FindControl("Label")).Text;
    dr["ColumnName2"] = ((Label)row.Cells[1].FindControl("Label")).Text;
    dt.Rows.Add(dr);
   }
 }
 
GridViewManagers.DataSource = dt;
GridViewManagers.DataBind();

Monday, October 3, 2011

Two Databound Fields in Gridview column

Boundfields are great in the Gridview, but they do have their limitations.
One is that it only has room for one bound field. So, what do you do when you want two or data fields.
For example, First and Last names returned to the same column.
Turn the BoundField into a TemplateField, with a label in it:

<asp:templatefield>
 <itemtemplate>               
  <asp:label id="lblname" runat="server" text="<%# Eval("Lname") +, "" + Eval("Fname") %>" />            
 </itemtemplate>
</asp:templatefield>

Hire Me

Follow me on Facebook

Follow me

Do you find this Blog helpful?

Follow by Email

About Me

My Photo
Expert Senior Software Developer

Microsoft Business Card