using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Configuration;
using System.Data;
public partial class FormCreationWithDataStoraget : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void sbmt_Click(object sender, EventArgs e)
{
string connectionString = ConfigurationManager.ConnectionStrings["Data Source=RAJIM -PC;Initial Catalog=RajiDatabase;Integrated Security=True"].ConnectionString;
string insertSql = "INSERT INTO FamilyDetails(FirstName,LastName,Gender,Age,Relationship,MobileNumber)" + "values(@FirstName,@LaseName,@Gender,,@Age,@,@MobileNumber)";
SqlConnection conn = new SqlConnection(connectionString);
SqlCommand scmd = new SqlCommand();
scmd.Connection = conn;
scmd.CommandType = CommandType.Text;
scmd.CommandText = insertSql;
SqlParameter firstname = new SqlParameter("@FirstName", SqlDbType.VarChar, 40);
firstname.Value = tbx.Text.ToString();
scmd.Parameters.Add(firstname);
SqlParameter lastname = new SqlParameter("@LaseName", SqlDbType.VarChar, 40);
lastname.Value = tbx1.Text.ToString();
scmd.Parameters.Add(lastname);
SqlParameter gender=new SqlParameter("@Gender",SqlDbType.VarChar,40);
gender.Value = rbt.SelectedItem.ToString();
scmd.Parameters.Add(gender);
SqlParameter age = new SqlParameter("@Age", SqlDbType.Int);
age.Value = tbx2.Text.ToString();
scmd.Parameters.Add(age);
SqlParameter relationship = new SqlParameter("@Relationship", SqlDbType.VarChar, 40);
relationship.Value = tbx3.Text.ToString();
scmd.Parameters.Add(relationship);
SqlParameter mobilenumber=new SqlParameter("@MobileNumber",SqlDbType.VarChar, 10);
mobilenumber.Value = tbx4.Text.ToString();
scmd.Parameters.Add(mobilenumber);
try
{
conn.Open();
scmd.ExecuteNonQuery();
Response.Write("User Registration successful");
}
catch (SqlException ex)
{
string errorMessage = "Error in registering user";
errorMessage += ex.Message;
throw new Exception(errorMessage);
}
finally
{
conn.Close();
}
}
}
答案 0 :(得分:1)
看起来这一行导致了您的问题:
string insertSql = "INSERT INTO FamilyDetails(FirstName,LastName,Gender,Age,Relationship,MobileNumber)" + "values(@FirstName,@LaseName,@Gender,,@Age,@,@MobileNumber)";
具体做法是:
@FirstName,@LaseName,@Gender,,@Age,@,@MobileNumber
应该是:
@FirstName,@LaseName,@Gender,@Age,@Relationship,@MobileNumber
答案 1 :(得分:0)
问题是这一行:
string connectionString = ConfigurationManager.ConnectionStrings["Data Source=RAJIM -PC;Initial Catalog=RajiDatabase;Integrated Security=True"].ConnectionString;
没有检索任何对象,因为您没有ConnectionString
定义了您的web.config
,其名称为"数据源= RAJIM ..."所以基本上在它结束时调用.ConnectionString
会破坏它。
添加"数据源= RAJIM ..."作为web.config
中的连接字符串行(有关连接字符串here的更多信息)。
为连接字符串命名后,即" MyConnectionString"然后将您的代码更改为:
string connectionString = ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;