Reputation: 75
i have a gridview with 2 fields property,values and contains 3 textboxes. when i enter the values,i kept some textboxes as empty,i need to check that empty textboxes.And that empty values don't want to insert into database. How can i solve this problem???
This is my code
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)
{
}
}
Upvotes: 0
Views: 168
Reputation: 14216
Best Idea is use required field validator for that textbox. Then you can add double checking like
string.IsNullOrEmpty(tb.Text)
Upvotes: 1
Reputation: 19870
You need to reorganize you code to first get the textbox control, then check for a non-empty string. If non-empty, then do the DB insert.
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();
}
}
Upvotes: 1
Reputation: 5636
You may try for
If(tb.Text!= string.Empty)
{
//Do your stuff
}
Or
If(tb.Text!="")
{
//Do your stuff
}
Or, Try to check for null
or Empty
before insert
query.
if (!string.IsNullOrEmpty("tb.Text"))
{
// Do Your stuff
}
Hope it works.
Upvotes: 1
Reputation: 3046
Is this ok ?
//Code
TextBox tb = (TextBox)gvr.FindControl("TextBox2");//value
string txt = tb.Text;
If(tb.Text!=string.IsNullOrEmpty)
{
//Do your stuff
}
Upvotes: 1