C# - 只有文本行将存储在数据库中?

时间:2012-07-20 11:45:19

标签: c# sql-server datagridview

当我输入datagridview文本框时,下一行会自动生成。

如何制止?

当我点击Insert按钮时,空行也存储在数据库中,这就是为什么我要问如何自动停止行生成?

我只想将文本ROW存储在数据库中,null或空行不存储在数据库中?

 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

1 个答案:

答案 0 :(得分:4)

AllowUserToAddRows 属性设置为false

但是根据你的代码,你必须检查你的外观并检查单元格的值,如果这些是null或不使用这样的东西

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

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