Hi,MeghaPatel
I have created sample code which fullfill requirement.
C#
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
this.BindGrid();
}
private void BindGrid()
{
string conString = @"Server=.;Database=Test;uid=sa;pwd=pass@123";
using (SqlConnection con = new SqlConnection(conString))
{
using (SqlCommand cmd = new SqlCommand("SELECT * FROM Users_Test", con))
{
cmd.CommandType = CommandType.Text;
using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
{
using (DataTable dt = new DataTable())
{
sda.Fill(dt);
dataGridView1.AutoGenerateColumns = true;
dataGridView1.DataSource = dt;
}
}
}
}
}
private void button1_Click(object sender, EventArgs e)
{
foreach (DataGridViewRow row in dataGridView1.Rows)
{
int Id = Convert.ToInt32(row.Cells["id"].Value);
string City = Convert.ToString(row.Cells["City"].Value);
Update(Id, City);
}
}
private void Update(int id, string city)
{
string conString = @"Server=.\SQL2005;Database=Test;uid=sa;pwd=pass@123";
using (SqlConnection con = new SqlConnection(conString))
{
using (SqlCommand cmd = new SqlCommand("Update Users_Test SET City = @City Where Id = @id", con))
{
con.Open();
cmd.Parameters.AddWithValue("@Id", id);
cmd.Parameters.AddWithValue("@city", city);
cmd.ExecuteNonQuery();
con.Close();
}
}
}
}
VB
Public Partial Class Form1
Inherits Form
Public Sub New()
InitializeComponent()
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs)
Me.BindGrid()
End Sub
Private Sub BindGrid()
Dim conString As String = "Server=.;Database=Test;uid=sa;pwd=pass@123"
Using con As New SqlConnection(conString)
Using cmd As New SqlCommand("SELECT * FROM Users_Test", con)
cmd.CommandType = CommandType.Text
Using sda As New SqlDataAdapter(cmd)
Using dt As New DataTable()
sda.Fill(dt)
dataGridView1.AutoGenerateColumns = True
dataGridView1.DataSource = dt
End Using
End Using
End Using
End Using
End Sub
Private Sub button1_Click(sender As Object, e As EventArgs)
For Each row As DataGridViewRow In dataGridView1.Rows
Dim Id As Integer = Convert.ToInt32(row.Cells("id").Value)
Dim City As String = Convert.ToString(row.Cells("City").Value)
Update(Id, City)
Next
End Sub
Private Sub Update(id As Integer, city As String)
Dim conString As String = "Server=.\SQL2005;Database=Test;uid=sa;pwd=pass@123"
Using con As New SqlConnection(conString)
Using cmd As New SqlCommand("Update Users_Test SET City = @City Where Id = @id", con)
con.Open()
cmd.Parameters.AddWithValue("@Id", id)
cmd.Parameters.AddWithValue("@city", city)
cmd.ExecuteNonQuery()
con.Close()
End Using
End Using
End Sub
End Class
I hope help you.