[英]how to create a sql temp table and insert data into it using a sql command (C#)
我确定了一个包含gridview
的c#
表单。 我想在按钮单击时将选定的行数据插入到临时表中。 我已经尝试过了,但是没有用。 它显示错误:
字符串或二进制数据将被截断。 该语句已终止
下面是我的代码:
private void button1_Click(object sender, EventArgs e)
{
int i = 0;
List<int> ChkedRow = new List<int>();
for (i = 0; i <= dataGridView1.RowCount - 1; i++)
{
if (Convert.ToBoolean(dataGridView1.Rows[i].Cells["Column1"].Value) == true)
{
ChkedRow.Add(i);
}
}
if (ChkedRow.Count == 0)
{
MessageBox.Show("Select Items to view report");
return;
}
foreach (int j in ChkedRow)
{
String ConnectionString1 = @"Data Source=.\SQLEXPRESS;Initial Catalog=tempdb;Integrated Security=True;Pooling=False";
cnnStr = @"create table ##gridtemp (itmcod varchar(7)) INSERT INTO ##gridtemp (itmcod)
VALUES ('" + dataGridView1.Rows[j].Cells["title"].Value.ToString() + "');";
try
{
using (SqlConnection cs = new SqlConnection(ConnectionString1))
{
using (cmd = new SqlCommand(cnnStr, cs))
{
cs.Open();
cmd.ExecuteNonQuery();
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
MessageBox.Show("Records Added Succesfully");
}
private void button1_Click(object sender, EventArgs e)
{
SqlConnection conn1 = new SqlConnection(@"Data Source=.\sqlexpress;Initial Catalog=tempdb;Integrated Security=True");
SqlCommand cmd1 = new SqlCommand("create table ##gridtemp (itmcod varchar(MAX))", conn1);
conn1.Open();
cmd1.ExecuteNonQuery();
DataTable dts = new DataTable();
SqlBulkCopy bulkCopy = new SqlBulkCopy(conn1);
bulkCopy.DestinationTableName = "##gridtemp";
bulkCopy.WriteToServer(dts);
conn1.Close();
int i = 0;
List<int> ChkedRow = new List<int>();
for (i = 0; i <= dataGridView1.RowCount - 1; i++)
{
if (Convert.ToBoolean(dataGridView1.Rows[i].Cells["Column1"].Value) == true)
{
ChkedRow.Add(i);
}
}
if (ChkedRow.Count == 0)
{
MessageBox.Show("Select Items to view report");
return;
}
foreach (int j in ChkedRow)
{
String ConnectionString1 = @"Data Source=.\SQLEXPRESS;Initial Catalog=tempdb;Integrated Security=True;Pooling=False";
cnnStr = @"INSERT INTO ##gridtemp (itmcod)
VALUES ('" + dataGridView1.Rows[j].Cells["itmcod"].Value.ToString() + "');";
try
{
using (SqlConnection cs = new SqlConnection(ConnectionString1))
{
using (cmd = new SqlCommand(cnnStr, cs))
{
cs.Open();
cmd.ExecuteNonQuery();
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
MessageBox.Show("Records Added Succesfully");
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.