C# 如何将文本框中的数据添加到数据库表
我是一名学生,刚开始用C#学习asp.net 我正在使用visual Studio 2015和MSSQL Server 2012。我在从webform向数据库表中添加数据时遇到问题 我已成功建立连接,但无法从文本框在数据库表中插入数据 我已经在很多地方搜索过了,但没能做到 有谁能告诉我做这件事的简单而准确的方法吗C# 如何将文本框中的数据添加到数据库表,c#,asp.net,database,database-connection,C#,Asp.net,Database,Database Connection,我是一名学生,刚开始用C#学习asp.net 我正在使用visual Studio 2015和MSSQL Server 2012。我在从webform向数据库表中添加数据时遇到问题 我已成功建立连接,但无法从文本框在数据库表中插入数据 我已经在很多地方搜索过了,但没能做到 有谁能告诉我做这件事的简单而准确的方法吗 SqlConnection con= (Connection Name) 如果您使用的数据库中没有主键,请继续执行此操作 SqlCommand query = new SqlComm
SqlConnection con= (Connection Name)
如果您使用的数据库中没有主键,请继续执行此操作
SqlCommand query = new SqlCommand("Insert into TABLE values ("+txtsample1.Text+")",con)
如果是主键,请注明字段名
SqlCommand query = new SqlCommand("Insert into TABLE (column1) values ("+txtsample1.Text+")",con)
库马尔:我不确定你们是否面临着将任何数据插入数据库或从文本框中捕获文本,然后将其插入数据库的问题。 然而,我将努力解决这两个问题。 要插入到数据库中,您可以访问 正如已经回答的那样 现在要捕获文本froim textbox,您可以使用HtmlElementClass
HtmlElement txtBox = null;
HtmlDocument doc = webBrowser1.Document;
if (doc != null)
{
txtBox = doc.GetElementByID("TxtboxelementId");
string txtValue=txtBox.InnerHtml
}
ASPX页面:
<form id="form1" runat="server">
<div>
<asp:TextBox ID="txtValue" runat="server"></asp:TextBox>
<asp:Button ID="btnInsert" runat="server" Text="Button" OnClick="btnInsert_Click" />
</div>
</form>
protected void Page_Load(object sender, EventArgs e)
{
}
private void InsertValue(string value)
{
using (SqlConnection con = new SqlConnection("YOUR_CONNECTION_STRING")) //Creating connection object
{
try
{
using (SqlCommand cmd = new SqlCommand("INSERT INTO YOUR_TABLE_NAME (Field_Name) VALUES (@value)", con))
{
if (con.State == System.Data.ConnectionState.Closed) con.Open();
cmd.Parameters.AddWithValue("@value", value); // Adding parameter with value to command object
int result = cmd.ExecuteNonQuery(); // Executing query and it returns no of rows affected.
if (result > 0) Response.Write("Successful."); // Checking if no of rows affected is > 0 meaning value successfully inserted.
}
}
catch (SqlException ex) //Handling SQL Exceptions
{
this.LogErrors(ex);
}
}
}
private void LogErrors(Exception ex)
{
// Write error log logic here
}
protected void btnInsert_Click(object sender, EventArgs e) // insert data button click event handler
{
this.InsertValue(this.txtValue.Text);
}
请插入一些迄今为止您尝试过的代码。主要是HTML表单、保存到数据库的方法和表的结构。它帮助人们帮助你。