TECHNOLOGIES
FORUMS
JOBS
BOOKS
EVENTS
INTERVIEWS
Live
MORE
LEARN
Training
CAREER
MEMBERS
VIDEOS
NEWS
BLOGS
Sign Up
Login
No unread comment.
View All Comments
No unread message.
View All Messages
No unread notification.
View All Notifications
Answers
Post
An Article
A Blog
A News
A Video
An EBook
An Interview Question
Ask Question
Forums
Monthly Leaders
Forum guidelines
Shyja Abraham
NA
69
0
object reference not set to an instance of an object c sharp
Feb 3 2011 7:46 AM
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.
Reply
Answers (
4
)
Asp.net Project with Sql connection
How to use keypress event in web application in C#