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.

Jean PaulRank #32 · 38.5K reputationPosted Feb 3, 2011, 3:07 AM EST
I believe the exception is occurring in some Value.ToString()
It would be difficult to locate the error from the above statement.
You can try the following to make the code looks easier.
1. Instead of passing the values to the method cn.insert() directly..
Set the values in a separate variable like:
string name = dataGridView1.Rows[i].Cells[0].Value.ToString();
string address = dataGridView1.Rows[i].Cells[1].Value.ToString();
Soon you can find which row cell is throwing exception.
2. Use meaningful constants for Cells[0] like:
dataGridView1.Rows[i].Cells[COL_NAME] etc.
3. The class connection should be as Connection (case)
Regards,
Jean Paul
Suthish NairRank #92 · 22.8K reputationPosted Feb 3, 2011, 7:24 AM EST
Sam HobbsRank #107 · 20.5K reputationPosted Feb 3, 2011, 10:23 AM EST
There are many other ways to get most of the programming done for you.
Suthish NairRank #92 · 22.8K reputationPosted Feb 4, 2011, 8:41 AM EST
Query resolved?
If yes, then tick the checkbox above "Do you like this Answer".
Will be helpful to others also for finding the solution