Please help me with my code

Newbie Spellweaver
Joined
Sep 21, 2014
Messages
32
Reaction score
1
C# Need help

Any Idea, what is wrong with my code?
error says -> ExecuteNonQuery: Connection property has not been initialized.

any body can correct my code please...

#region RegisterButton
private void btnRegister_Click(object sender, EventArgs e)
{
try
{
SqlConnection con = new SqlConnection(@"Data Source=TEST-PC\SQLEXPRESS;Initial Catalog=DBServer;Integrated Security=True");
con.Open();
SqlCommand cmd = new SqlCommand(@"insert into TblAccounts(Names,Lnames,Midnames,Address,Cnumber)
values ('" + txbxName.Text + "','" + txbxLName.Text + "', '" + txbxMName.Text + "', '" + txbxAddrss.Text + "', '" + txbxCNum.Text + "')");



cmd.ExecuteNonQuery();
con.Close();
}
catch (Exception ex) {MessageBox.Show(ex.Message);}
}
#endregion

Also I have created a stored procedure on the database side. But I can't remember how to use this into c#

create procedure storeAccs
(
@Names nvarchar(50),
@Lnames nvarchar(50),
@midnames nvarchar(50),
@Address nvarchar(50),
@Cnumber int,
)
as
begin

insert into TblAccounts(Names,Lnames,Midnames,Address,Cnumber)
valuesTblAccounts @Names,@Lnames @midnames,@Address,@Cnumber)


end
 
Re: [Tutorial Requests]

However that this is not a tutorial request, you need to pass ur SqlConnection object to the SqlCommand.
In the SqlCommand you should have a second constructor with Query,SqlConnection.



How to pass ur SqlConnection object to the SqlCommand?
 
Re: [Tutorial Requests]

new SqlConnection(string query, SqlConnection connect);

Check MSDN.


Thank you so much ben.

I have figure it out what is miss with my code. It's just I have for got to initialize the connection.

SqlCommand cmd = new SqlCommand(@"insert into TblAccounts(Names,Lnames,Midnames,Address,Cnumber)
values ('" + txbxName.Text + "','" + txbxLName.Text + "', '" + txbxMName.Text + "', '" + txbxAddrss.Text + "', '" + txbxCNum.Text + "')",con);
 
Back