如何动态地将行添加到表中?

时间:2018-02-28 15:50:03

标签: c# sql asp.net

我有一个联系表单,用户可以在其中添加1个或更多(最多5个)联系人。用户单击“保存”后,程序需要检查提交的联系人数,并相应地作为单独的行插入到Contacts_Table中。例如,如果用户提供3个联系人,则应将3行插入数据库。这里的问题是能够实现目标,但我正在努力减少代码行数。

以下是示例代码:

        string internalContact = "insert into InternalContact("
                                  + "Phone, FirstName, Surname)"
                                  + "values (@Phone, @FirstName, @Surname)";

        using (OleDbConnection conn1 = new OleDbConnection(ConnString))
        {
            using (OleDbCommand cmd1 = new OleDbCommand(internalContact, conn1))
            {
                conn1.Open();
                cmd1.CommandType = CommandType.Text;

                cmd1.Parameters.Add("FirstName", OleDbType.VarChar).Value = TextBox34.Text;
                cmd1.Parameters.Add("Surname", OleDbType.VarChar).Value = TextBox42.Text;                   
                cmd1.Parameters.Add("Phone", OleDbType.VarChar).Value = TextBox45.Text;

                cmd1.ExecuteNonQuery();

                if (TextBox64.Text != "")
                {
                    cmd1.Parameters.Clear();

                    cmd1.Parameters.Add("FirstName", OleDbType.VarChar).Value = TextBox64.Text;
                    cmd1.Parameters.Add("Surname", OleDbType.VarChar).Value = TextBox65.Text;                        
                    cmd1.Parameters.Add("Phone", OleDbType.VarChar).Value = TextBox69.Text;

                    cmd1.ExecuteNonQuery();
                }
                conn1.Close();
            }
        }

1 个答案:

答案 0 :(得分:0)

我会创建一个结构列表并将所有联系信息传递给该方法。

struct contactInfo
    {
        public string FirstName;
        public string Surname;
        public string Phone;
    }



private void insertContacts (List<contactInfo> pList)
{
using (OleDbConnection conn1 = new OleDbConnection(ConnString))
    {            
            conn1.Open();

        foreach (contactInfo info in pList)
        {
           using (OleDbCommand cmd1 = new OleDbCommand(internalContact, conn1))
            {

            cmd1.CommandType = CommandType.Text;
            cmd1.Parameters.Add("FirstName", OleDbType.VarChar).Value = info.FirstName;
            cmd1.Parameters.Add("Surname", OleDbType.VarChar).Value = info.Surname;                  
            cmd1.Parameters.Add("Phone", OleDbType.VarChar).Value = info.Phone;

            cmd1.ExecuteNonQuery();
             }

           }
            conn1.Close();
        }
    }