如何在ASP.NET中使用C#将文本字段中的值插入到SQL Server数据库中 [英] How to insert a value from textfield into the sql server database using c# in asp.net

查看:281
本文介绍了如何在ASP.NET中使用C#将文本字段中的值插入到SQL Server数据库中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我是asp.net的初学者.我在UI中有2个文本字段,我想使用asp.net中的C#将这些值输入到SQL Server数据库中.
我该如何解决问题.我尝试使用Google搜索,但没有发现任何具体且有用的内容.

任何帮助表示赞赏.

谢谢.

解决方案

您的标记是这样的

 <   asp:textbox     id   ="     runat   =" 服务器"  xmlns:asp   #unknown" / > 
<   asp:textbox     id   ="   runat   服务器"  xmlns:asp   #unknown" / > 
<   asp:button     id   ="   runat   服务器" 文本  提交到数据库"  onclick   ="     ="  #unknown" /  受保护的 无效 Button1_Click(对象发​​件人,EventArgs e)
{
字符串 Text1 = TextBox1.Text;
字符串 Text2 = TextBox2.Text;


字符串 connectionString = " 

SqlConnection sqlConnection =  SqlConnection(connectionString);

字符串 insertStatement = "  + Text1 +  ," + Text2 + " 

SqlCommand sqlCommand =  SqlCommand(insertStatement,sqlConnection);

尝试
{
sqlConnection.Open();
sqlCommand.ExecuteNonQuery();

}
最终
{
sqlConnection.Close();
}


} 


Hi,

I m a beginner in asp.net. I have 2 text fields in UI,I want to enter values from those into the SQL server database using C# in asp.net.

How do i go about solving the problem. I tried googling things out,but didn''t find anything specific and helpful.

Any help is appreciated.

Thanks.

解决方案

Your mark up goes like this

<asp:textbox id="TxtBox1" runat="server" xmlns:asp="#unknown" />
<asp:textbox id="TxtBox2" runat="server" xmlns:asp="#unknown" />
<asp:button id="Button1" runat="server" text="Submit to DataBase" onclick="Button1_Click" xmlns:asp="#unknown" />




The Column1 and column2 are the 2 columns into which you want to insert the text box values.Prepare you connection string as per your configuration.

Your Code Behind Contains method to handle button click event.Include Using System.Data.SqlClient; in code behind


protected void Button1_Click(Object sender,EventArgs e)
{
string Text1=TextBox1.Text;
string Text2=TextBox2.Text;


string connectionString="Data Source=servername;Initial Catalog=DataBaseName;User ID=sa;Password=YourPassword;"

SqlConnection sqlConnection=new SqlConnection(connectionString);

string insertStatement="INSERT INTO TableName(column1,column2) VALUES "+Text1+","+Text2+");"

SqlCommand sqlCommand=new SqlCommand(insertStatement,sqlConnection);

try
{
sqlConnection.Open();
sqlCommand.ExecuteNonQuery();

}
finally
{
sqlConnection.Close();
}


}


这篇关于如何在ASP.NET中使用C#将文本字段中的值插入到SQL Server数据库中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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