4
Reply

object reference not set to an instance of an object c sharp

Shyja Abraham

Shyja Abraham

Feb 3 2011 7:46 AM
13.3k
hai

i have a form with datagridview and a button,i need to insert the values of datagridview into the sql database when i click the button.

i use this code


                   connection cn;
                     SqlCommand cmd;

private void button1_Click(object sender, EventArgs e)
        {
            cn = null;
            cn = new connection();
            cmd = new SqlCommand();
            cmd.Connection = cn.connect();
for (int i = 0; i < dataGridView1.Rows.Count; i++)
             {
            cn.insert(dataGridView1.Rows[i].Cells[0].Value.ToString(), dataGridView1.Rows[i].Cells[1].Value.ToString(), dataGridView1.Rows[i].Cells[2].Value.ToString(), textBox1.Text);
}
MessageBox.Show("datainserted");
}


in the class.cs


  public class connection
    {

        public SqlConnection con;
        public SqlCommand cmd;
        public SqlConnection connect()
        {
            con = new SqlConnection("server=HP-B67A56C6431D\\HORIZON;uid=sa;password=horizon;database=shyja;");
            
           
            con.Open();
            return con;
            
           
        }


        public void insert(string id, string name, string pho,string add)
        {
            cmd = new SqlCommand();
            cmd.Connection = connect();
            cmd.CommandText = "insert";
            cmd.CommandType = System.Data.CommandType.StoredProcedure;
            cmd.Parameters.Add("id", SqlDbType.VarChar).Value = id;
            cmd.Parameters.Add("name", SqlDbType.VarChar).Value = name;
            cmd.Parameters.Add("pho", SqlDbType.VarChar).Value = pho;
            cmd.Parameters.Add("add", SqlDbType.VarChar).Value = add;
            cmd.ExecuteNonQuery();
        }

        

   }


but the error object reference not set to an instance of an object c sharp in the bolded line.plz help.


        

Answers (4)