将数据从文本框保存到数据库 [英] Save data from textbox to database

查看:94
本文介绍了将数据从文本框保存到数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些文本框和一个提交按钮.
我能够从数据库中检索数据并将其显示在文本框中
我想更新此数据,然后将其保存回数据库.
我该怎么办?
我应该在按钮的单击处理程序中使用什么代码?数据,因为您需要存储特定行或显示数据的任何主键值,并将该值存储在Viewstate或会话中,之后在Button_Click上就可以获取所有文本框的值并通过存储的值更新数据库在视图状态或会话中.

您还可以将主键值存储在隐藏字段"中,也可以在视图状态或会话位置使用查询字符串.


在会话变量中检索主键值,然后将其写为updatebtn_click
中的以下代码

受保护的 void  updatebtn_Click(对象发​​件人,EventArgs e)
{

SqlCommand cmd =  SqlCommand(" ,Conn);
//  Conn是您创建的SqlConnection对象.
cmd.Parameters.AddWithValue(" ,TextBox1.Text);
cmd.Parameters.AddWithValue(" ,TextBox2.Text);
cmd.Parameters.AddWithValue(" ,txtid.Text);

尝试
{
Conn.open();
cmd.ExecuteNonQuery();
Conn.close();
}
捕获(异常exp)
{
 exp;
}
} 


希望对您有帮助.
谢谢


我认为了解基本的ADO.NET将使您能够非常轻松地执行此操作以及所有数据库操作.这是绝对可以为您提供帮助的链接:

了解ADO.NET的初学者教程 [ ^ ]


I have some textboxes and a submit button.
I am able to retrieve data from database and shown them to the textboxes
I want to update this data and then to save them back to the database.
How can I do that?
What code should I use in the click handler of the button?

解决方案

As you are saying you have successfully shown the data on textboxes and now you are trying to update same data, ok for that you have need to store any Primary Key value of particular row or shown data and store that value in Viewstate or session, after that on Button_Click you can get the value of all the textboxes and update the database by the stored value in the viewstate or sassion.

you can also store the Primary Key value in the Hidden Field or you can use query string also on the place of viewstate or sassion.


Retrieve your primary key value in Session varaibles and then write the following code in updatebtn_click

Protected void updatebtn_Click(object sender, EventArgs e)
{

SqlCommand cmd= new SqlCommand("Update TableName Set Column1=@Column1,Column2=@Column2 Where ID=@ID",Conn);
//Conn is SqlConnection object that You have created.
cmd.Parameters.AddWithValue("@Column1",TextBox1.Text);
cmd.Parameters.AddWithValue("@Column2",TextBox2.Text);
cmd.Parameters.AddWithValue("@ID",txtid.Text);

try
{
Conn.open();
cmd.ExecuteNonQuery();
Conn.close();
}
Catch(Exception exp)
{
throw exp;
}
}


Hope, It will help you.
Thanks


I think knowing the basic ADO.NET will enable you to do this and all DB operations very very easily. Here is a link that will definitely help you:

A Beginner''s Tutorial for Understanding ADO.NET[^]


这篇关于将数据从文本框保存到数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆