How to write insert code in if.....Else in button click

Posted by Dn2010 under ASP.NET on 2/22/2011 | Points: 10 | Views : 2950 | Status : [Member] | Replies : 4
hi friends,

how to write insert code in if.....Else in button click.

cmd.CommandText = "insert into reg values('" + txtname.Text + "','" +
txtcity.Text + "','" + txtstate.Text + "')";


or

cmd.CommandText = "insert into reg values('" + txtname.Text + "','" + txtcity.Text + "')";


database:
create table reg(name varchar(250),city varchar(200),state varchar(200))

code:


protected void btn_register_Click(object sender, EventArgs e)
{
OpenConnection(con);
cmd.Connection = con;
cmd.CommandText = "insert into reg values('" + txtname.Text + "','" +
txtcity.Text + "','" + txtstate.Text + "')";
Response.Write("<script>alert('Inserted Successfully')</script>");
cmd.ExecuteNonQuery();
con.Close();
}

please correct it.

thanks.




Responses

Posted by: Karthikanbarasan on: 2/22/2011 [Member] [Moderator] [Microsoft_MVP] [MVP] Silver | Points: 25

Up
0
Down
Hi,

Can you please post your requirement in brief? are you going to prepare the insert statement inside the if loop? and what is the condition?

Thanks
Karthik
www.f5Debug.net

Dn2010, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: Madhu.b.rokkam on: 2/23/2011 [Member] [MVP] Bronze | Points: 25

Up
0
Down
Hi,

Its always advisable to use stored procs then inline SQL queries. So better go with that.

Comming to your question, Put the alert message after the Execute non query and try.
Mention the CommandType as text



Thanks and Regards
Madhu

Dn2010, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: Madhuk on: 2/23/2011 [Member] Starter | Points: 25

Up
0
Down
As other members said using the parameters is always better option
As I understand you want to use queries in if else like correct me if I am wrong.
string strCmd=" ";

if(condition)
{
strCmd = "insert into reg(name,city,state) values('" + txtname.Text + "','" +
txtcity.Text + "','" + txtstate.Text + "')";
}
else
{
strCmd = "insert into reg(name,city) values('" + txtname.Text + "','" + txtcity.Text + "')";
}
//then assign strCmd to commandtext
cmd.CommandText=strCmd;



Dn2010, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: Naimishforu on: 2/23/2011 [Member] [MVP] Bronze | Points: 25

Up
0
Down
Cool

Thanks,
Naimish
http://dotnetinterview.zxq.net/
http://naimishpandya.blogspot.in/

Dn2010, if this helps please login to Mark As Answer. | Alert Moderator

Login to post response