如何在sql server中插入数据datagridview行值。 [英] How to insert data datagridview rows values in sql server.

查看:99
本文介绍了如何在sql server中插入数据datagridview行值。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的datagriview控件有多行,如SNO,ITEM,DESCRIPTION,QUANTITY,当我尝试在sql server中插入datagridview的多行时,它会占用前一行值而其余行不插入。以下是我的代码块。

善意建议...提前谢谢



My datagriview control having multiple rows like SNO, ITEM, DESCRIPTION, QUANTITY, when I am trying to insert datagridview's multiple rows in sql server it is taking top one row values and rest of the rows not inserting.following is my code block.
kindly suggest...thanks in advance

SqlConnection cn = new SqlConnection(constring);
           foreach (DataGridViewRow Row in dgvholidays.Rows)   //dgv holiday
           {
               if (Row.Cells[0].Value != null)
               {
                   int myear = Convert.ToInt32(Row.Cells[0].Value.ToString());
                   string holname =Convert.ToString(Row.Cells[1].Value);
                   DateTime dt = Convert.ToDateTime(Row.Cells[2].Value);   // Convert.ToInt32(Row.Cells[0].Value.ToString())
                   DateTime dt1 = Convert.ToDateTime(Row.Cells[3].Value);
                   int days = Convert.ToInt32(Row.Cells[4].Value.ToString());
                   dgvholidays.Columns[2].DefaultCellStyle.NullValue = string.Empty;
                   dgvholidays.Columns[3].DefaultCellStyle.NullValue = string.Empty;
                   SqlCommand cmd = new SqlCommand("Update Holiday set mYear='" + myear + "',holidayName='" + holname + "',dtFrom='" + dt.ToLongTimeString() + "',dtTo='" + dt1.ToLongTimeString() + "',tDays='" + days + "',Compcode='" + ccode + "' where IsActice=1", cn);
                   cmd.Connection.Open();
                   cmd.ExecuteNonQuery();
                   cmd.Connection.Close();
               }
           }

推荐答案

共享代码没有插入逻辑,相反它是用于更新。

注意:我正在使用答案部分,因为您在此处共享的代码中仍然存在问题。请看一下。



查看 WHERE 查询条件。你错过了吗?

The shared code doesn't have the logic for insertion, instead it is meant for updation.
Note: I am using the answer section as you still have issue in the peiece of code you have shared here. Please have a look.

Hav a look at WHERE condition of your query. Are you are missing someting like-
WHERE IsActice=1 AND SomeId=@SomeId --IsActice or IsActive??



您当前的查询应该使用 IsActice = 1 更新所有记录,因此您应该看到仅在上次更新时完成更改。



注意:您应该使用参数化查询或存储过程而不是内联查询来避免SQL注入。


Your current query should update all the records with IsActice=1 and hence you should see the changes done only in the last updation.

Note: You should use parameterized query or stored procedure instead of inline queries to avoid SQL Injection.


这篇关于如何在sql server中插入数据datagridview行值。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆