我的网络表单未成功保存到数据库

时间:2016-10-18 09:26:14

标签: c# sql asp.net database forms

我的表单没有将Texbox中的文本保存到数据库中。我的.cs CodeFile可能有问题,但我无法解决。

很可能是我的连接字符串。

我的网络表单

<form id="form1" runat="server">
    <div>
        <table>
            <tr>
                <td>
                    Enter selection text:
                </td>
                <td>
                    <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
                </td>
            </tr>
                <td colspan="2" align="center">
                    <asp:Button ID="Button1" runat="server" Text="Submit" />
                </td>
            </tr>
        </table>
    </div>
</form>

以下是我的代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Data;
using System.Configuration;
using System.Data.SqlClient;

public partial class _Default : System.Web.UI.Page 
{
    SqlConnection con = new SqlConnection(@"Data Source=db65225900.db.1and1.com; Initial Catalog=db211255182; User ID=dbo652259000; Password=Password");

    protected void Page_Load(object sender, EventArgs e)
    {
    }

    protected void Button1_Click1(object sender, EventArgs e)
    {
        con.Open();
        SqlCommand cmd = con.CreateCommand();
        cmd.CommandType = CommandType.Text;
        cmd.CommandText = "insert into homepageSelection values('"+TextBox1.Text+"')";
        cmd.ExecuteNonQuery();
        con.Close();    
    }
}

我的MsSQL设置如下:

1列:selectionText nvarchar(3000)

3 个答案:

答案 0 :(得分:7)

在aspx中缺少按钮单击事件定义

 <asp:Button ID="Button1" runat="server" Text="Submit" OnClick="Button1_Click1" />
                                             ---------------^

答案 1 :(得分:1)

SqlConnection适用于SQL Server。您需要MySqlConnection - 这不是.NET Framework的一部分。因此,如果您还必须使用MySqlCommand对象而不是SqlCommand对象,那么这是一种更好的方法。

这是 MySql ,而不是 SQL 。所以你需要连接到MySql。为此,您需要从MySQL official website下载并安装MySQL Connector / NET。

然后你可以看看Connect C# to MySQL看看如何连接MySQL数据库并使用C#运行不同的Insert,Update,Select,Delete命令

最后但并非最不重要的是,您必须在OnClick="Button1_Click1"

中添加asp:Button

答案 2 :(得分:0)

您需要在插入语句中设置列名称

cmd.CommandText = "insert into homepageSelection (ColumnName) values('"+TextBox1.Text+"')";

你也错过了点击事件

<asp:Button ID="Button1" runat="server" Text="Submit" OnClick="Button1_Click1" />