简体   繁体   中英

C# - only text row will be store in database?

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

在此处输入图片说明

Set AllowUserToAddRows Property to false

But according to your code you must have to place check in your for look and check the values of cell if those are null or not by using something like this

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

Because if you stop grid to add rows automatically then you have to do that manually to insert new rows. So the best thing is you must let the grid add news rows. But place the check of null values in your code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM