Hi kankon,
Check the example.
SQL
CREATE TABLE UserInfo(id INT IDENTITY PRIMARY KEY,name VARCHAR(50),civilid INT,fileid INT,country VARCHAR(50),countryNew VARCHAR(50))
INSERT INTO UserInfo VALUES('Hesham',21254568,456,'','india')
HTML
<asp:GridView runat="server" ID="gvUserInfo" AutoGenerateColumns="false">
<Columns>
<asp:BoundField DataField="id" HeaderText="Id" />
<asp:BoundField DataField="name" HeaderText="Name" />
<asp:BoundField DataField="civilid" HeaderText="Civil Id" />
<asp:BoundField DataField="fileid" HeaderText="File Id" />
<asp:BoundField DataField="country" HeaderText="Country" />
<asp:BoundField DataField="countryNew" HeaderText="Country New" />
<asp:TemplateField>
<ItemTemplate>
<asp:Button Text="Edit" runat="server" OnClick="OnEdit" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:HiddenField ID="hfCountry" runat="server" />
ID:<asp:TextBox ID="txtId" runat="server"></asp:TextBox><br />
Country:<asp:TextBox ID="txtCountry" runat="server"></asp:TextBox><br />
<asp:Button Text="Update" runat="server" OnClick="OnUpdate" />
Namespaces
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
Code
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
this.BindGridView();
}
}
protected void OnUpdate(object sender, EventArgs e)
{
string conString = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(conString))
{
using (SqlCommand cmd = new SqlCommand("UPDATE UserInfo SET country = @Country, countryNew = @CountryNew WHERE id = @Id", con))
{
cmd.Parameters.AddWithValue("@Country", hfCountry.Value);
cmd.Parameters.AddWithValue("@CountryNew", txtCountry.Text);
cmd.Parameters.AddWithValue("@Id", txtId.Text);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
this.BindGridView();
}
protected void OnEdit(object sender, EventArgs e)
{
GridViewRow row = (sender as Button).NamingContainer as GridViewRow;
hfCountry.Value = row.Cells[5].Text;
txtId.Text = row.Cells[0].Text;
}
private void BindGridView()
{
string conString = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
string query = "SELECT * FROM UserInfo";
using (SqlConnection con = new SqlConnection(conString))
{
using (SqlCommand cmd = new SqlCommand(query, con))
{
using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
{
using (DataTable dt = new DataTable())
{
sda.Fill(dt);
gvUserInfo.DataSource = dt;
gvUserInfo.DataBind();
}
}
}
}
}