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.
4 Replies
Know the answer? Post it — somebody with the same question will find it here.
Sign in to answer this question
It is the same account you read, post and publish with — and you will come straight back to this page.
Jean PaulPosted Feb 3, 2011, 8:07 AM
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 NairPosted Feb 4, 2011, 1:41 PM
Query resolved?
If yes, then tick the checkbox above "Do you like this Answer".
Will be helpful to others also for finding the solution
Sam HobbsPosted Feb 3, 2011, 3:23 PM
There are many other ways to get most of the programming done for you.
Suthish NairPosted Feb 3, 2011, 12:24 PM