简体   繁体   English

将文本框绑定到数据库(C#Web开发人员)

[英]Binding textboxes to database (C# web developer)

I am using Microsoft Visual Web Developer 2010 Express. 我正在使用Microsoft Visual Web Developer 2010 Express。 I have been trying to enter my textbox input into a database table I created. 我一直在尝试将文本框输入输入到我创建的数据库表中。 I ran into a problem using the DataBinding property (located under the BindTextBoxes method at the bottom). 我在使用DataBinding属性(位于底部的BindTextBoxes方法下)时遇到了问题。 I searched the internet and found out that the DataBinding property does not exist in Web Developer. 我在互联网上搜索,发现Web Developer中不存在DataBinding属性。 Is there an alternate way to transfer the textbox input into a database table? 是否有将文本框输入转移到数据库表中的替代方法?

Here is database part of my code (in C#): 这是我的代码(在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));
     }
   }
 }

You could always write your own SQL for inserting data from your text boxes. 您总是可以编写自己的SQL,以便从文本框中插入数据。 You'll need to setup a SqlConnection and SqlCommand object. 您将需要设置SqlConnection和SqlCommand对象。 Then you'll need to define the SQL on the command and set up the parameters to prevent SQL injection. 然后,您需要在命令上定义SQL并设置参数以防止SQL注入。 Something like this: 像这样:

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();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM