如何使用文本框插入数据库 [英] how to insert database using a textbox
本文介绍了如何使用文本框插入数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
< body >
< 表格 id = form1 runat = < span class =code-keyword> server >
< div >
< textbox id = txt / >
< br / >
< / div >
< / form >
< / body >
解决方案
那么我们从上面的代码中了解了什么?!在发布此类问题之前,您可以在 CodeProject [ ^ ]并在 Google [ ^ ]。
您的代码会是这样的......
string sqlquery = INSERT INTO [tableName](ColumnName)VALUES(@textboxValue);
SqlCommand command = new SqlCommand(sqlquery,connection);
string testString = testTextBox.Text;
command.Parameters.AddWithValue( textboxValue,testString);
在.aspx页面中使用一个按钮,然后在文本框中运行服务器,如:
< body >
< 表格 id = form1 runat = < span class =code-keyword> server >
< div >
< 文本框 id = txt runat = server / >
< br / >
< asp:按钮 ID = Button1 runat = server 文字 = 保存 < span class =code-attribute> OnClick = button1_Click / > ;
< / div >
< / form >
< / body >
private void button1_Click(对象s ender,EventArgs e)
{
SqlConnection conn = new SqlConnection(@Data Source = .\SQLEXPRESS; AttachDbFilename = | DataDirectory | \Database1.mdf; Integrated Security = True; User Instance = True ;);
try
{
SqlCommand cmd = new SqlCommand(INSERT INTO customers(firstName,lastName,address,city)VALUES('wee','weeee','dfddd','weee' ),conn);
conn.Open();
cmd.ExecuteNonQuery();
MessageBox.Show(Connection Succeful);
}
catch(SqlException ex)
{
MessageBox.Show(有一个错误+ ex);
}
最后
{
conn.Close();
MessageBox.Show(Connection Closed);
}
}
如果有帮助,请接受回答并投票。
<body>
<form id="form1" runat="server">
<div>
<textbox id="txt" />
<br />
</div>
</form>
</body>
解决方案
So what do we understand from your above code?! Before posting such type questions you can do a search in CodeProject[^] and in Google[^].
Your code will be something look like...
string sqlquery = "INSERT INTO [tableName] (ColumnName) VALUES (@textboxValue)"; SqlCommand command = new SqlCommand(sqlquery , connection); string testString = testTextBox.Text; command.Parameters.AddWithValue("textboxValue", testString);
Use one button in your .aspx page and runat server you text box like:
<body> <form id="form1" runat="server"> <div> <textbox id="txt" runat="server" /> <br /> <asp:Button ID="Button1" runat="server" Text="Save" OnClick="button1_Click" /> </div> </form> </body>
private void button1_Click(object sender, EventArgs e) { SqlConnection conn = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database1.mdf;Integrated Security=True;User Instance=True;"); try { SqlCommand cmd = new SqlCommand("INSERT INTO customers(firstName,lastName,address,city) VALUES ('wee','weeee','dfddd', 'weee')", conn); conn.Open(); cmd.ExecuteNonQuery(); MessageBox.Show("Connection Succeful"); } catch (SqlException ex) { MessageBox.Show("There is an Error" + ex); } finally { conn.Close(); MessageBox.Show("Connection Closed"); } }
Accept as answer and vote if help to you.
这篇关于如何使用文本框插入数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文