0
     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();

    }

my program compare the each element from datagridview with every element from Uint table from database to prevent duplicate in database if element from datagridvoew is not Similar to element in uint table in database implement insert statement Why the program does not insert any data to database? (Does not implement the insert statement )

4

2 回答 2

0

在第一个 for 循环中将找到的变量初始化为 false :

found = false;

以便每次迭代都将其设置为初始状态。否则,如果一旦将其设置为 true,则始终变为 true。这就是您的插入语句未执行的原因。

所以你的 for 循环应该是这样的:

    for (int i = 0; i < dataGridView1.Rows.Count; i++)
    {
        found = false;

        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("تمت الاضافه");


        }
    }
于 2013-11-02T20:05:51.657 回答
0

您如何要求数据库检查条目是否存在?

var unitName = dataGridView1.Rows[i].Cells[0].Value.ToString();
var command = new SqlCommand("SELECT COUNT(*) FROM Units WHERE Unit_name = @name", connection);
command.Parameters.AddWithValue("@name", unitName);

int result = (int)command.ExectureScalar();

if(result == 0) // no entry
{
     //Insert.
}
于 2013-11-02T20:49:07.227 回答