Ubivashka
Ubivashka

Reputation: 1

why insert is failed&

Don't get data to IDProduct, but product.IDProvider has number. I try different methods. Help me, please

con.Open();
int id;
SqlCommand s = new SqlCommand("select * from Provider where Name = '" + TProvider.Text + "'", con);
SqlDataReader dr1 = s.ExecuteReader();
if (dr1.Read())
{
    id = dr1.GetInt32(0);
    product.IDProvider = id;
    dr1.Close();
    SqlCommand senddata = new SqlCommand("insert into Product (Name, Type, IDProvider, Metal, ColorMetal, GemStone, Weight, Sample, Price, CountProduct, Picture) values (@Name, @Type, @IDProvider, @Metal, @ColorMetal, @GemStone, @Weight, @Sample, @Price, @CountProduct, @Picture)", con);
    senddata.Parameters.AddWithValue("@Name", product.Name);
    senddata.Parameters.AddWithValue("@Type", product.Type);
    senddata.Parameters.AddWithValue("@IDProvider", product.IDProvider);                  
    senddata.Parameters.AddWithValue("@Metal", product.Metal);
    senddata.Parameters.AddWithValue("@ColorMetal", product.Color);
    senddata.Parameters.AddWithValue("@Gemstone", product.Gemstone);
    senddata.Parameters.AddWithValue("@Weight", product.Weight);
    senddata.Parameters.AddWithValue("@Sample", product.Sample);
    senddata.Parameters.AddWithValue("@Price", product.Price);
    senddata.Parameters.AddWithValue("@CountProduct", product.CountProduct);
    MemoryStream ms = new MemoryStream();
    product.img.Save(ms, product.img.RawFormat);
    senddata.Parameters.AddWithValue("@Picture", ms.ToArray());
    senddata.ExecuteNonQuery();
}

Upvotes: 0

Views: 41

Answers (1)

AKX
AKX

Reputation: 168824

You're using select * – there's absolutely no guarantee the zeroth field (dr1.GetInt32(0)) is what you want.

Explicitly declare the field you want; assuming it's ProviderID:

SqlCommand s = new SqlCommand("select ProviderID from Provider where Name = '" + TProvider.Text + "'", con);

Then, to avoid SQL injection issues, parametrize that like you already do with the other command:

SqlCommand s = new SqlCommand("select ProviderID from Provider where Name = @Name", con);
s.Parameters.AddWithValue("@Name", TProvider.Text);

Upvotes: 1

Related Questions