I agree with the previous answer that this is a very dangerous approach. If the user is allowed to enter a value into `this.statename.Text` they might type
'; DROP DATABASE; --
The quote closes the open quote making it an empty string, the semicolon terminates the statement and SQL engine then processes the DROP DATABASE as a fresh statement. Ouch!
The `--` following the DROP DATABASE makes the rest of the line a comment. Check out this site: http://michaeldaw.org/sql-injection-cheat-sheet
Anyway...
I think where you're going wrong syntactically is that you are putting single quotes around your select statement in the insert statement, thereby turning it from a select statement into a string literal. I.e.:
values( ..., 'select code from state where name='Karnataka'')
Furthermore, since it already has single quotes in it, it becomes syntactically correct.
My SQL is a bit rusty but I don't think you can have select statements inside VALUES(). I think they have to be literals.
Try this instead. It uses a SELECT to insert into the table:
String str = "INSERT INTO branch(Code,Name,metro,state)"
+ " SELECT '" + this.txtbranchcode.Text + "','"
+ this.txtbranchname.Text + "','"
+ this.cmbmetro.SelectedIndex + "',"
+ " code FROM state WHERE name='" + this.statename.Text + "'";
Better would be to validate the statename (that it has only letters and no quotes or semicolons etc). Better still would be to send it as a parameterised query - this avoids all the so called SQL injection attacks.