2013-05-30 41 views
0

我有一个gridview有2个字段的属性,值和包含3个文本框。 当我输入值时,我将一些文本框保留为空,我需要检查空的文本框。并且空值不想插入到数据库中。我怎么解决这个问题???如何检查在asp.net中的文本框的空白?

这是我的代码

foreach (GridViewRow gvr in GridView1.Rows) 
{ 
    string strcon1; 
    strcon1 = ConfigurationManager.ConnectionStrings["fwma_devConnectionString"].ConnectionString; 

    SqlConnection con1 = new SqlConnection(strcon1); 
    con1.Open(); 

    SqlCommand com3 = new SqlCommand(strcon); 

    TextBox tb = (TextBox)gvr.FindControl("TextBox2");//value 

    string txt = tb.Text; 

    Label propertylabel = (Label)gvr.FindControl("Label4");//id-property 

    com3.CommandText = "INSERT INTO BrandProperties(PropertyID,BrandID,[Values]) values('" + propertylabel.Text + "','" + B_id.Text + "','" + tb.Text + "')"; 
    com3.Connection = con1; 
    com3.ExecuteNonQuery(); 

    con1.Close(); 

    if (tb.Text == String.Empty) 
    { 

    } 
} 
+0

你需要表现出一定的警告时,这是空的?或者放弃插入? – Fals

+0

只是想放弃那个空的文本框插入。不想显示任何警告。 –

+0

尝试在插入查询之前检查“null”或“Empty”,而不是在“插入”查询之后检查。 – Rahul

回答

1

您需要重新组织代码以先获取文本框控件,然后检查非空字符串。如果非空,则执行数据库插入。

foreach (GridViewRow gvr in GridView1.Rows) 
{ 
    TextBox tb = (TextBox)gvr.FindControl("TextBox2");//value 

    if (!string.IsNullOrEmpty(tb.Text)) 
    { 
    string strcon1; 
    strcon1 = ConfigurationManager.ConnectionStrings["fwma_devConnectionString"].ConnectionString; 

    SqlConnection con1 = new SqlConnection(strcon1); 
    con1.Open(); 

    SqlCommand com3 = new SqlCommand(strcon); 

    Label propertylabel = (Label)gvr.FindControl("Label4");//id-property 

    com3.CommandText = "INSERT INTO BrandProperties(PropertyID,BrandID,[Values]) values('" + propertylabel.Text + "','" + B_id.Text + "','" + tb.Text + "')"; 
    com3.Connection = con1; 
    com3.ExecuteNonQuery(); 

    con1.Close(); 
    } 
} 
1

这是好吗?

//代码

TextBox tb = (TextBox)gvr.FindControl("TextBox2");//value 
string txt = tb.Text; 
If(tb.Text!=string.IsNullOrEmpty) 
{ 
    //Do your stuff 
} 
+0

只是一个提示!使用string.IsNullOrEmpty这种比较! – Fals

+0

当然,可以做到。 – iamCR

+0

在数据库中插入相同的空白行。 –

1

您可以尝试为

If(tb.Text!= string.Empty) 
{ 
    //Do your stuff 
} 

或者

If(tb.Text!="") 
{ 
    //Do your stuff 
} 

或者,尝试前insert查询检查nullEmpty

if (!string.IsNullOrEmpty("tb.Text")) 
{ 
    // Do Your stuff 
} 

希望它有效。

+0

nop ..在数据库中插入相同的空白行。 –

+1

尝试最后的逻辑'!string.IsNullOrEmpty(“tb.Text”)'.. – Rahul

+0

相同.. :(在数据库行中插入空白文本框 –

1

最好的想法是使用该文本框所需的字段验证器。然后,您可以添加双重检查像

string.IsNullOrEmpty(tb.Text)

相关问题