2

When I type in datagridview textbox next row automatically generated.

How to stop that ?

When I clicked on Insert button empty row also store in database that is why I'm asking how to stop automatically row generate ?

I want only text ROW will be store in database, null or empty row does not store in database ??

 string StrQuery;
using (SqlConnection conn = new SqlConnection(connection string))
{
using (SqlCommand comm = new SqlCommand())
{
comm.Connection = conn;
conn.Open();
for(int i=0; i< dataGridView1.Rows.Count;i++)
{
StrQuery= @"INSERT INTO std VALUES ('"
+ dataGridView1.Rows[i].Cells["sname"].Value +"', '"
+ dataGridView1.Rows[i].Cells["class"].Value +"')";
comm.CommandText = StrQuery;
comm.ExecuteNonQuery();
}
}
}

enter image description here

4

1 回答 1

4

AllowUserToAddRows属性设置为 false

但是根据您的代码,您必须检查您的 for 外观并使用类似这样的方法检查单元格的值是否为空

        for(int i=0; i< dataGridView1.Rows.Count;i++) 
    { 
if (dataGridView1.Rows[i].Cells["sname"]!=null)
{
    StrQuery= @"INSERT INTO std VALUES ('" 
    + string.IsNullOrWhiteSpace(dataGridView1.Rows[i].Cells["sname"].Value) +"', '" 
    + string.IsNullOrWhiteSpace(dataGridView1.Rows[i].Cells["class"].Value) +"')"; 
    comm.CommandText = StrQuery; 
    comm.ExecuteNonQuery(); 
}
    } 

因为如果您停止网格自动添加行,那么您必须手动插入新行。所以最好的事情是你必须让网格添加新闻行。但是在您的代码中检查空值。

于 2012-07-20T11:52:29.297 回答