Dear Mohal92,
Refer below sample.
Database
I have made use of the following table Customers with the schema as follows.
I have already inserted few records in the table.
You can download the database table SQL by clicking the download link below.
Download SQL file
HTML
<asp:GridView runat="server" ID="gvCustomers" AutoGenerateColumns="false">
<Columns>
<asp:BoundField DataField="CustomerId" HeaderText="ID" />
<asp:BoundField DataField="Name" HeaderText="Name" />
<asp:BoundField DataField="Country" HeaderText="Country" />
<asp:CommandField ButtonType="Button" ShowEditButton="true" HeaderText="Button" />
</Columns>
</asp:GridView>
<br />
<asp:Button Text="Save" runat="server" OnClick="OnSave"/>
Namespaces
C#
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
VB.Net
Imports System.Data
Imports System.Data.SqlClient
Imports System.Configuration
Code
C#
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
this.BindGrid();
}
}
private void BindGrid()
{
string conn = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(conn))
{
using (SqlCommand cmd = new SqlCommand("SELECT CustomerId, Name, Country FROM Customers", con))
{
using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
{
using (DataTable dt = new DataTable())
{
sda.Fill(dt);
gvCustomers.DataSource = dt;
gvCustomers.DataBind();
}
}
}
}
}
protected void OnSave(object sender, EventArgs e)
{
DataTable dt = new DataTable();
for (int j = 0; j < gvCustomers.Columns.Count - 1; j++)
{
dt.Columns.Add(gvCustomers.Columns[j].HeaderText);
}
for (int i = 0; i < gvCustomers.Rows.Count; i++)
{
DataRow dr = dt.NewRow();
for (int j = 0; j < gvCustomers.Columns.Count - 1; j++)
{
dr[gvCustomers.Columns[j].HeaderText] = gvCustomers.Rows[i].Cells[j].Text;
}
dt.Rows.Add(dr);
}
}
VB.Net
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
If Not Me.IsPostBack Then
Me.BindGrid()
End If
End Sub
Private Sub BindGrid()
Dim conn As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
Using con As SqlConnection = New SqlConnection(conn)
Using cmd As SqlCommand = New SqlCommand("SELECT CustomerId, Name, Country FROM Customers", con)
Using sda As SqlDataAdapter = New SqlDataAdapter(cmd)
Using dt As DataTable = New DataTable()
sda.Fill(dt)
gvCustomers.DataSource = dt
gvCustomers.DataBind()
End Using
End Using
End Using
End Using
End Sub
Protected Sub OnSave(ByVal sender As Object, ByVal e As EventArgs)
Dim dt As DataTable = New DataTable()
For j As Integer = 0 To gvCustomers.Columns.Count - 1 - 1
dt.Columns.Add(gvCustomers.Columns(j).HeaderText)
Next
For i As Integer = 0 To gvCustomers.Rows.Count - 1
Dim dr As DataRow = dt.NewRow()
For j As Integer = 0 To gvCustomers.Columns.Count - 1 - 1
dr(gvCustomers.Columns(j).HeaderText) = gvCustomers.Rows(i).Cells(j).Text
Next
dt.Rows.Add(dr)
Next
End Sub
Screenshot