0

我有多个textboxes进入一个名为dbo.skills

dbo.Skills SkillID (PK- AutoIncrement) | SkillName 

因此,当我使用此方法时,名称不会被存储,但只有 SkillID 会自动递增。 这是我的 .cs 代码

 public void InsertSkillInfo()
    {


        String KKStech = @"Data Source=USER-PC\SQLEXPRESS;Initial Catalog=KKSTech;Integrated Security=True";
        SqlConnection conn = new SqlConnection(KKStech);

        try
        {

            for (int i = 1; i <= 4; i++)
            {
                conn.Open();

                //string skill = (TextBox)((Page.FindControl("TextBox" + i.ToString()))).Text;

                var skill = "";
                var control = Page.FindControl("TextBox" + i.ToString()) as TextBox;
                if (control != null)
                {
                    skill = control.Text;
                }
                const string sqlStatement = "INSERT INTO Skills (SkillName) VALUES (@SkillName)";
                SqlCommand cmd = new SqlCommand(sqlStatement, conn);
                cmd.CommandType = CommandType.Text;
                cmd.Parameters.AddWithValue("@SkillName", skill);
                cmd.ExecuteNonQuery();
                conn.Close();
            }
        }

        catch (System.Data.SqlClient.SqlException ex)
        {
            string msg = "Insert Error:";
            msg += ex.Message;
            throw new Exception(msg);
        }

在文本框中输入值后,表格如下所示 -

Dbo.Skills
SkillID | SkillName
1       | 
2       | 
3       | 
4       | 

ASP 代码:

 <asp:Label ID="Label1" class="caption" runat="server" Text="Skill Name"></asp:Label>
    <asp:TextBox ID="TextBox1" class="box" runat="server"></asp:TextBox> <br /> <br />

    <asp:Label ID="Label2" class="caption" runat="server" Text="Skill Name"></asp:Label>
    <asp:TextBox ID="TextBox2" class="box" runat="server"></asp:TextBox> <br /> <br />

    <asp:Label ID="Label3" class="caption" runat="server" Text="Skill Name"></asp:Label>
    <asp:TextBox ID="TextBox3" class="box" runat="server"></asp:TextBox> <br /> <br />

    <asp:Button ID="Button1" class="box" runat="server" Text="Insert" 
        onclick="Button1_Click" /> <br /><br /><br />
4

0 回答 0