2013-04-01 80 views
0

我正在使用Microsoft Visual Web Developer 2010 Express。我一直在嘗試將我的文本框輸入輸入到我創建的數據庫表中。我遇到了使用DataBinding屬性的問題(位於底部的BindTextBoxes方法下)。我搜索了互聯網,發現Web Developer中不存在DataBinding屬性。有沒有一種替代方法將文本框輸入傳輸到數據庫表中?將文本框綁定到數據庫(C#Web開發人員)

這裏是我的代碼數據庫的一部分(在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

你總是可以編寫自己的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(); 
+0

非常感謝。我嘗試運行我的項目,但遇到以下錯誤:「無法識別的轉義序列」爲以下行:SqlConnection connUserDetails = new SqlConnection(「DataSource =。\ SQLEXPRESS; AttachDbFilename = D:\ Users \ synthesis \ Documents \ Visual Studio 2010 \ Projects \ Practical \ Practical \ App_Data \ UserDetails.mdf; Integrated Security = True; User Instance = True「);我認爲在該行中正斜槓「/」有問題 – synthesis

+0

put @在包含「\」的c#中的任何字符串之前,如新SqlConnection(@「DataSource ...」),並且將解決該錯誤 –

+1

感謝它成功了! – synthesis