You are here:

ASP.NET/How Can I Store One Table Id In Another Table

Advertisement


Question
I have tried this code

con.Open();
SqlCommand cmd = new SqlCommand("insert into Exe_ContactDetails values(@Name,@Mobile,@Address,@UserId)", con);
cmd.CommandType = CommandType.Text;
string str = "Select ID from Team_Registration where UserName= '" + Session["New"] + "'";
//int N = Convert.ToInt32(str);
cmd.Parameters.AddWithValue("@Name", txtName.Text.ToString());
cmd.Parameters.AddWithValue("@Mobile", txtMobile.Text.ToString());
cmd.Parameters.AddWithValue("@Address", txtAddress.Text.ToString());
cmd.Parameters.AddWithValue("@UserId", str);
cmd.ExecuteNonQuery();
con.Close();


when I executed this code (Conversion failed when converting the nvarchar value 'Select ID from Team_Registration where UserName= 'madhu'' to data type int.)getting this error.
Please suggest to me how can I erase this error.

How can I store the Team_registration ID in another table column as UserId

Answer
You need bit of changes in the code
con.Open();
string str = "Select ID from Team_Registration where UserName= '" + Session["New"] + "'";
SqlCommand cmdId = new SqlCommand(str, con);
int N = Convert.ToInt32(cmdId.ExecuteScalar());

SqlCommand cmd = new SqlCommand("insert into Exe_ContactDetails values(@Name,@Mobile,@Address,@UserId)", con);
cmd.CommandType = CommandType.Text;
         
         
cmd.Parameters.AddWithValue("@Name", txtName.Text.ToString());
cmd.Parameters.AddWithValue("@Mobile", txtMobile.Text.ToString());
cmd.Parameters.AddWithValue("@Address", txtAddress.Text.ToString());
cmd.Parameters.AddWithValue("@UserId", N);
cmd.ExecuteNonQuery();
con.Close();

Try the above code.

ASP.NET

All Answers


Answers by Expert:


Ask Experts

Volunteer


Aman Bhullar

Expertise

1. Asp.Net(C#, VB) 2. IIS(6.0) 3. C# 4. Classic ASP 5. JavaScript

Experience

I have nearly 7 Years of Experience in Field of IT with Asp.net Developer (Portal, Dynamic websites ,CRM's, CMS) Visual studio.net 2003,2005 (VB.net , C#.net) Database (SQL server 2005), Stored procedures IIS 5-6 JavaScript, CSS, DHTML, XML

Education/Credentials
Hold Masters in Computer Applications

Awards and Honors
Contributor Member of Asp.net Achieved Master Certification(Programming for ASP.NET) [Experts-exchange.com]

©2016 About.com. All rights reserved.