In this blog we are going to illustrate how to transfer the GridView data to DataTable.
To transfer GridView to DataTable:
We add button in .aspx page where the GridView display the data. By clicking this button user transfer the GridView data to DataTable.
Code for .aspx page:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:BoundField DataField="EmpId" HeaderText="EmpId" ItemStyle-Width="30" />
<asp:BoundField DataField="EmpName" HeaderText="EmpName" ItemStyle-Width="150" />
<asp:BoundField DataField="EmpAddress" HeaderText="EmpAddress" ItemStyle-Width="150" />
</Columns>
</asp:GridView>
<br />
<br />
<asp:Button runat="server" ID="btn" OnClick="TransferDataToDataTable" Text="Transfer to Datatable" />
Add the following Namespaces:
using System.Data;
using System.Configuration;
using System.Data.SqlClient;
Binding the GridView
In page Load , GridView will display the data of employees table inside the Employee_system_database
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
string ConnectString = ConfigurationManager.ConnectionStrings["ConnectString"].ConnectionString;
using (SqlConnection con = new SqlConnection(ConnectString))
{
using (SqlCommand cmd = new SqlCommand("SELECT EmpId, EmpName, EmpAddress FROM Employees"))
{
cmd.Connection = con;
using (SqlDataAdapter sd = new SqlDataAdapter(cmd))
{
DataTable dt = new DataTable();
sd.Fill(dt);
Gridview.DataSource = dt;
Gridview.DataBind();
}
}
}
}
}
Transfer the data from GridView to DataTable in ASP.Net
When a user clicked the “Transfer to Datatable “ button then data display in gridview will transferred into the datatable.
protected void TransferDataToDataTable(object sender, EventArgs e)
{
DataTable EmployeeDataTable = new DataTable("Employees");
foreach (TableCell cell in Gridview.HeaderRow.Cells)
{
EmployeeDataTable.Columns.Add(cell.Text);
}
foreach (GridViewRow row in Gridview.Rows)
{
EmployeeDataTable.Rows.Add();
for (int i = 0; i < row.Cells.Count; i++)
{
EmployeeDataTable.Rows[row.RowIndex][i] = row.Cells[i].Text;
}
}
}
0 Comment(s)