how to update table data in asp.net?
Here is the sql database table creating code:
We need a Gridview to view data first:
We also pass a parameter (id) by click edit button from Gridview then we need to load a single row data parameter wise for edit by above table.
Here is all code behind:
Finally our output is here:
CREATE TABLE tblCustomerA stored procedure to Update:
(
[id] [int] IDENTITY(1,1) NOT NULL,
[FirstName] [nvarchar](50) NULL,
[LastName] [nvarchar](50) NULL,
[Email] [nvarchar](200) NULL,
[Phone] [nvarchar](50) NULL
)
create proc sp_update_tblCustomer
(
@id int,
@name nvarchar(50),
@last nvarchar(50),
@email nvarchar(50),
@phone nvarchar(50)
)
as
begin
update tblCustomer set
FirstName =@name,
LastName=@last,
Email=@email,
Phone =@phone
where id = @id
end
<asp:GridView runat="server" ID="GridView1" class="table table-bordered">
<Columns>
<asp:TemplateField HeaderText="Edit">
<ItemTemplate>
<a href="inserCustomer.aspx?id=<%#Eval("id") %>" >Edit</a>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
We also pass a parameter (id) by click edit button from Gridview then we need to load a single row data parameter wise for edit by above table.
Here is all code behind:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
showMain();
}
}
private void showMain()
{
string id = Request.QueryString["id"];
if (id!=null)
{
ShowDataIdWise();
}
}
private void ShowDataIdWise()
{
string Edit_Id = Request.QueryString["id"];
var dt = new DataTable();
var da = new SqlDataAdapter("SELECT * from tblCustomer where id=" + Edit_Id, con);
con.Open();
da.Fill(dt);
con.Close();
if (dt.Rows.Count > 0)
{
DataRow row = dt.Rows[0];
txtName.Text = Convert.ToString(row["FirstName"]);
txtLast.Text = Convert.ToString(row["LastName"]);
txtEmail.Text = Convert.ToString(row["email"]);
txtPhone.Text = Convert.ToString(row["phone"]);
}
}
protected void btnUpdate_Click(object sender, EventArgs e)
{
string Edit_Id = Request.QueryString["id"];
name = txtName.Text;
last = txtLast.Text;
email = txtEmail.Text;
phone = txtPhone.Text;
var cmd = new SqlCommand("sp_update_tblCustomer", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@id", Edit_Id);
cmd.Parameters.AddWithValue("@name", name);
cmd.Parameters.AddWithValue("@last", last);
cmd.Parameters.AddWithValue("@email", email);
cmd.Parameters.AddWithValue("@phone", phone);
con.Open();
int m = cmd.ExecuteNonQuery();
if (m != 0)
{
lblmsg.Text = "Data Updated Succesfully";
lblmsg.ForeColor = Color.Green;
}
con.Close();
}
Finally our output is here:
No comments