Showing posts with label button. Show all posts
Showing posts with label button. Show all posts

Friday, February 24, 2012

inserting to multiple fields using a button

I have multiple textboxes in a page. How do i make them insert their values to multiple fields on multiple tables using a button.

You can just execute some SqlCommands to insert data to different tables in the Click event of a button, for example:

protected void Button2_Click(object sender, EventArgs e)
{
using (SqlConnection conn = new SqlConnection(@."Data Source=labsh96223\iori2000;Integrated Security=SSPI;Database=tempdb"))
{
conn.Open();
string insertSql = @."Insert into myTbl_1 select @.id, @.name";
SqlCommand myCommand = new SqlCommand(insertSql, conn);
myCommand.Parameters.Add("@.id", SqlDbType.Int);
myCommand.Parameters.Add("@.name", SqlDbType.VarChar, 100);
myCommand.Parameters["@.id"].Value = Int32.Parse(TextBox1.Text);
myCommand.Parameters["@.name"].Value = TextBox2.Text;
int i = myCommand.ExecuteNonQuery();
myCommand.CommandText = @."Insert into myTbl_2 select @.id, @.Description";
myCommand.Parameters.Clear();
myCommand.Parameters.Add("@.id", SqlDbType.Int);
myCommand.Parameters.Add("@.Description", SqlDbType.VarChar, 1000);
myCommand.Parameters["@.id"].Value = Int32.Parse(TextBox3.Text);
myCommand.Parameters["@.name"].Value = TextBox4.Text;
i= myCommand.ExecuteNonQuery();
//execute other commands
}
}

Sunday, February 19, 2012

INSERTING or UPDATING automatically

i am using visual web developer 2005 and SQL Express 2005 with VB as the code behind

i have a button and in the button click event i have written codes to INSERT to a database table - it has one primary key

so when i click the button, if there is already a row with primary key fields value as 10 and if i try to INSERT with the same value in the primary key field there will occur primary key constraint

so , if i try to INSERT with the already existing primary key fields value, instead of INSERTing it should be UPDATEd without generating any error

please help me

In ur SQl procedure

Include


If exists (select [PrimaryKeyColumn] from UrTable where PrimarKey = @.PrimaryKey)

Update ...

else

Insert ...

Like this u get to check for existing key , if exists it will execute an update else an insert

Hope that helps u