简体   繁体   中英

Insert values from several textboxes into one column but creating a new row for each textbox value

I have a C# program to insert data into a SQL Server database. The database has a column and of course multiple rows can be created with data insert. In my Winforms program I have several textboxes that get data from another table, each textbox gets different data. I want to insert data from each textbox into the same column. However, I need each textbox value to go into its own row. Like this

ColumnName
-------------------
Value from textbox1
Value from textbox2

This is the code I have. The problem is that it inserts the values from the 2 textboxes in the same column like I want but in the same row.

This is the code:

string str = ConfigurationManager.ConnectionStrings["Connection"].ConnectionString;
SqlConnection con = new SqlConnection(str);
con.Open();

_ = TextBox1Text;
_ = TextBox1Text ;

String commandText = "INSERT INTO SQLTableName (ColumnName) VALUES (@ColumnName)";

if (con.State == ConnectionState.Open)
{
    SqlCommand cmmd = new SqlCommand(commandText, con);

    cmmd.Parameters.Add("@ColumnName", SqlDbType.Text);

    cmmd.Parameters["@ColumnName"].Value = TextBox1.Text + ' ' + TextBox2.Text;
}

Can anyone help me figure out how to get this done?

EDIT:

I modified the code as suggested in the comments and answer. However, when it enters the data into the database it saves the value from textbox1 into one row, but the value from textbox 2 is being saved twice one in each row.

String commandText = "INSERT INTO MyTable (ColumnName)Values(@ColumnName)";
if (con.State == ConnectionState.Open)
{
    SqlCommand cmmd = new SqlCommand(commandText, con)
    cmmd.Parameters.Add("@ColumnName", SqlDbType.Nvarchar, -1);
    cmmd.Parameters["@ColumnName"].Value = TextBox1.Text;
    cmmd.ExecuteNonQuery();
    cmmd.Parameters["@ColumnName"].Value = TextBox2.Text;
    cmmd.ExecuteNonQuery();
} 

You need to replace the line

cmmd.Parameters["@ColumnName"].Value = TextBox1.Text + ' ' + TextBox2.Text;

with the following:

cmmd.Parameters["@ColumnName"].Value = TextBox1.Text;
cmmd.ExecuteNonQuery();
cmmd.Parameters["@ColumnName"].Value =  TextBox2.Text;
cmmd.ExecuteNonQuery();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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