I wanted to insert a data to my database with textBox.
But I don't want to add duplicate ID to my database and I want to show a message box.
Actually I did it but when I want to add a new data which is different than all ID's, I get an error
NullReferenceException was unhandled (Object reference not set to an instance of an object)
This is my code
for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
if (textBox1.Text == dataGridView1.Rows[i].Cells[0].Value.ToString())
{
MessageBox.Show("This ID is already exist", "Something went wrong", MessageBoxButtons.OK, MessageBoxIcon.Warning);
textBox1.Focus();
return;
}
}
DataTable dt = new DataTable();
string query = "insert into InOrder(InodID, OrderNum, SuppID, CarID, Price, Amount, OrderDate) values ('" + textBox1.Text + "','" + textBox2.Text + "','" + textBox3.Text + "','" + textBox4.Text + "','" + textBox5.Text + "','" + textBox6.Text + "','" + dateTimePicker1.Text + "')";
SqlDataAdapter sda = new SqlDataAdapter(query, connect);
sda.Fill(dt);
dataGridView1.DataSource = dt;
MessageBox.Show("Your data successfully saved", "Congratulation", MessageBoxButtons.OK, MessageBoxIcon.None);
How can I solve this problem?