private void Save_Click(object sender, EventArgs e)
{
string strconn = @"Server=.\SQLEXPRESS;initial catalog=PharmacyV2;integrated security=true;";
SqlConnection conn = new SqlConnection(strconn);
//SqlCommand cmd = new SqlCommand();
DataSet ds = new DataSet();
conn.Open();
SqlDataAdapter da = new SqlDataAdapter("select * from Units",conn);
da.Fill(ds, "Units");
bool found = false;
for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
for (int j = 0; j < ds.Tables["Units"].Rows.Count; j++)
{
if (ds.Tables["Units"].Rows[j][0].ToString() == dataGridView1.Rows[i].Cells[0].Value.ToString())
{
found = true;
break;
}
}
if (found==false)
{
SqlCommand cmd;
cmd = new SqlCommand("insert into Units (Unit_name) values (@name)", conn);
cmd.Parameters.AddWithValue("@name", dataGridView1.Rows[i].Cells[0].Value.ToString());
cmd.ExecuteNonQuery();
MessageBox.Show("تمت الاضافه");
}
}
conn.Close();
}
我的程序從DataGridView的每個元素比較從UINT表從數據庫中每一個元素,以防止數據庫 重複,如果從datagridvoew元素不在數據庫 實現插入類似元素UINT表聲明 爲什麼程序不會將任何數據插入數據庫? (不執行插入語句)防止重複的數據庫條目
您有任何錯誤或異常消息? –
'dataGridView1.Rows.Count'的值是什麼?放置一個斷點並檢查它 – sll
並且配置那個SqlConnection對象,即:使用(SqlConnection conn = new SqlConnection(strconn)){}' – Stefan