Hi jochk12345,
Check this example. Now please take its reference and correct your code.
HTML
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:BoundField DataField="Id" HeaderText="Id" />
<asp:BoundField DataField="Name" HeaderText="Name" />
<asp:BoundField DataField="Country" HeaderText="Country" />
</Columns>
</asp:GridView>
<asp:Button Text="Update" runat="server" OnClick="OnUpdate" />
Code
C#
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
System.Data.DataTable dt = new System.Data.DataTable();
dt.Columns.AddRange(new System.Data.DataColumn[3] {
new System.Data.DataColumn("Id"),
new System.Data.DataColumn("Name"),
new System.Data.DataColumn("Country") });
dt.Rows.Add(1, "John Hammond", "United States");
dt.Rows.Add(2, "Mudassar Khan", "India");
dt.Rows.Add(3, "Suzanne Mathews", "France");
dt.Rows.Add(4, "Robert Schidner", "Russia");
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
protected void OnUpdate(object sender, EventArgs e)
{
System.Data.DataTable dt = new System.Data.DataTable();
dt.Columns.AddRange(new System.Data.DataColumn[3] {
new System.Data.DataColumn("Id"),
new System.Data.DataColumn("Name"),
new System.Data.DataColumn("Country") });
dt.Rows.Add(5, "Maria", "Austria");
dt.Rows.Add(6, "Ana Trujillo", "France");
dt.Rows.Add(7, "Suzanne Mathews", "Brazil");
for (int i = 0; i < GridView1.Rows.Count; i++)
{
if (dt.Rows.Count > i)
{
GridView1.Rows[i].Cells[0].Text = dt.Rows[i]["Id"].ToString();
GridView1.Rows[i].Cells[1].Text = dt.Rows[i]["Name"].ToString();
GridView1.Rows[i].Cells[2].Text = dt.Rows[i]["Country"].ToString();
}
}
}
VB.Net
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
If Not Me.IsPostBack Then
Dim dt As Data.DataTable = New Data.DataTable()
dt.Columns.AddRange(New Data.DataColumn(2) {
New Data.DataColumn("Id"),
New Data.DataColumn("Name"),
New Data.DataColumn("Country")})
dt.Rows.Add(1, "John Hammond", "United States")
dt.Rows.Add(2, "Mudassar Khan", "India")
dt.Rows.Add(3, "Suzanne Mathews", "France")
dt.Rows.Add(4, "Robert Schidner", "Russia")
GridView1.DataSource = dt
GridView1.DataBind()
End If
End Sub
Protected Sub OnUpdate(ByVal sender As Object, ByVal e As EventArgs)
Dim dt As Data.DataTable = New Data.DataTable()
dt.Columns.AddRange(New Data.DataColumn(2) {
New Data.DataColumn("Id"),
New Data.DataColumn("Name"),
New Data.DataColumn("Country")})
dt.Rows.Add(5, "Maria", "Austria")
dt.Rows.Add(6, "Ana Trujillo", "France")
dt.Rows.Add(7, "Suzanne Mathews", "Brazil")
For i As Integer = 0 To GridView1.Rows.Count - 1
If dt.Rows.Count > i Then
GridView1.Rows(i).Cells(0).Text = dt.Rows(i)("Id").ToString()
GridView1.Rows(i).Cells(1).Text = dt.Rows(i)("Name").ToString()
GridView1.Rows(i).Cells(2).Text = dt.Rows(i)("Country").ToString()
End If
Next
End Sub
Screenshot