我正在使用Microsoft Visual Web Developer 2010 Express。我一直在尝试将我的文本框输入输入到我创建的数据库表中。我使用DataBinding属性(位于底部的BindTextBoxes方法下)遇到了问题。我搜索了互联网,发现Web Developer中不存在DataBinding属性。是否有另一种方法将文本框输入传输到数据库表中?
这是我的代码的数据库部分(在C#中):
namespace WebApplication2
{
public partial class _Default : System.Web.UI.Page
{
//used to link textboxes with database
BindingSource bsUserDetails = new BindingSource();
//info stored in tables
DataSet dsUserDetails = new DataSet();
//manages connection between database and application
SqlDataAdapter daUserDetails = new SqlDataAdapter();
//create new SQL connection
SqlConnection connUserDetails = new SqlConnection("Data Source=.\SQLEXPRESS;AttachDbFilename=D:\Users\synthesis\Documents\Visual Studio 2010\Projects\Practical\Practical\App_Data\UserDetails.mdf;Integrated Security=True;User Instance=True");
protected void Page_Load(object sender, EventArgs e)
{
//link textboxes to relevant fields in the dataset
bsUserDetails.DataSource = dsUserDetails;
bsUserDetails.DataMember = dsUserDetails.Tables[0].ToString();
//call BindTextBoxes Method
BindTextBoxes();
private void BindTextBoxes()
{
txtBoxCell.DataBindings.Add(new Binding("Name entered into txtBox", bsUserDetails,
"Name column in database table", true));
}
}
}
答案 0 :(得分:0)
您可以随时编写自己的SQL,以便从文本框中插入数据。您需要设置SqlConnection和SqlCommand对象。然后,您需要在命令上定义SQL并设置参数以防止SQL注入。像这样:
StringBuilder sb = new StringBuilder();
sb.Append("INSERT INTO sometable VALUES(@text1,@text2)");
SqlConnection conn = new SqlConnection(connStr);
SqlCommand command = new SqlCommand(sb.ToString());
command.CommandType = CommandType.Text;
command.Parameters.AddWithValue("text1", text1.Text);
command.Parameters.AddWithValue("text2", text2.Text);
command.ExecuteNonQuery();