2013-05-30 40 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)

相關問題