【发布时间】:2012-09-10 02:49:28
【问题描述】:
我使用 C# Windows 窗体。我需要自动编号不重复。
我正在将文件 excel 导入到 datagridview 并为不重复生成字段“id”。
但不工作。
例如
首次导入。 身份证 |姓名 P001 => 自动生成 |一种 P002 => 自动生成 |乙
第二次进口。 身份证 |姓名 P001 => Auto Gen 但我需要 P003 | C P002 => Auto Gen 但我需要 P004 | D
代码:
SqlConnection Conn = new SqlConnection();
SqlCommand cmd = new SqlCommand();
StringBuilder sb = new StringBuilder();
SqlTransaction tr;
private void testExcel_Load(object sender, EventArgs e)
{
string appConn = ConfigurationManager.ConnectionStrings["connDB"].ConnectionString;
Conn = new SqlConnection();
if (Conn.State == ConnectionState.Open)
{
Conn.Close();
}
Conn.ConnectionString = appConn;
Conn.Open();
}
private void button1_Click(object sender, EventArgs e)
{
try
{
if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
TextBox1.Text = openFileDialog1.FileName;
File.ReadAllText(TextBox1.Text);
}
OleDbConnection conn = new OleDbConnection();
conn.ConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0; Data Source=" + TextBox1.Text + @";Extended Properties=""Excel 8.0; HDR=Yes; IMEX=1; ImportMixedTypes=Text; TypeGuessRows=0"" ";
OleDbCommand cmd = new OleDbCommand("SELECT * " + "FROM [SHEET1$]", conn);
DataSet ds = new DataSet();
OleDbDataAdapter ad = new OleDbDataAdapter(cmd);
ad.Fill(ds);
dataGridView1.DataSource = ds.Tables[0];
}
catch (Exception)
{
}
}
private void button2_Click(object sender, EventArgs e)
{
for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
tr = Conn.BeginTransaction();
sb.Remove(0, sb.Length);
sb.Append("INSERT INTO tbl_Asset (AsId,AsName)");
sb.Append("VALUES (@Asid,@AsName)");
string sqlSave = sb.ToString();
cmd.CommandText = sqlSave;
cmd.CommandType = CommandType.Text;
cmd.Connection = Conn;
cmd.Transaction = tr;
cmd.Parameters.Clear();
cmd.Parameters.Add("@Asid", SqlDbType.VarChar).Value = dataGridView1.Rows[i].Cells[0].Value;
cmd.Parameters.Add("@AsName", SqlDbType.VarChar).Value = dataGridView1.Rows[i].Cells[1].Value;
cmd.ExecuteNonQuery();
tr.Commit();
}
MessageBox.Show("Insert Done", "Result", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
private void button3_Click(object sender, EventArgs e)
{
int cellnum = 0;
for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
cellnum = cellnum + 1;
dataGridView1.Rows[i].Cells[0].Value = txtID.Text + "000" + cellnum;
}
}
非常感谢您抽出宝贵时间。 :)
【问题讨论】:
-
这里是一个网站,可以引导您了解如何设置自动编号字段 完成此谷歌搜索不到一秒钟 techonthenet.com/access/tables/autoinc.php
-
为什么不使用identity 列?
-
我尝试设置身份列。当点击 Gen 时出错。
-
SQL Server 不允许将标识属性添加到已填充的字段。您可能必须重新创建表并使用
set identity_insert table_name on;填充它以填充当前数据。
标签: c# sql-server windows winforms sql-server-2008