I have this code and when I run it gives this error ExecuteNonQuery: Connection property has not been initialized. And I have sql database. its name is Cost. I have this code and when I run it gives this error ExecuteNonQuery: Connection property has not been initialized. And I have sql database. its name is Cost. My code is:
namespace Accountingss
{
public partial class WebForm1 : System.Web.UI.Page
{
public SqlConnection conn;
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Connect(string cmdtxt, Hashtable parameters)
{
conn = new SqlConnection();
string connString = @"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Cost.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True";
conn.ConnectionString = connString;
SqlCommand cmd = new SqlCommand();
cmd.CommandText = cmdtxt;
cmd.Parameters.Clear();
var ieParams = parameters.GetEnumerator();
while (ieParams.MoveNext())
{
cmd.Parameters.AddWithValue(ieParams.Key.ToString(), ieParams.Value.ToString());
//cmd.Parameters.Add(new SqlParameter(ieParams.Key.ToString(), ieParams.Value.ToString()));
}
conn.Open();
cmd.ExecuteNonQuery();
//SqlDataAdapter costdataAdpater = new SqlDataAdapter();
//DataTable costdataTable = new DataTable();
}
protected void Button1_Click(object sender, EventArgs e)
{
string insert = "INSERT INTO Cost (Type, Amount) VALUES (@type, @amount)";// +type.Text + ',' + a.Text + ")";
var addpTA = new Hashtable();
addpTA.Add("@type", txtType.Text);
addpTA.Add("@amount", txtAmount.Text);
Connect(insert, addpTA);
}
}
}