4

I have got this part of code which do SELECT SqlCommand for column char(20) but the result is always returns 0 - this is because I don't know how to improve my code so it would return char(20) - value which is in this column inserted.

 SqlCommand sc = new SqlCommand("SELECT doklad FROM netpokl WHERE id_dok=" + newIdentity, spojeni);
 spojeni.Open();

 int id_dok = Convert.ToChar(sc.ExecuteScalar());

 spojeni.Close();

 MessageBox.Show("" + id_dok);

 SqlCommand sc2 = new SqlCommand("UPDATE kliplat set doklad=@doklad WHERE id="+newIdentity, spojeni);
 sc2.Parameters.AddWithValue("@doklad", id_dok);

 spojeni.Open();
 sc2.ExecuteNonQuery();
 spojeni.Close();

Would anyone help me improve my code please?

2
  • 5
    Not an answer to your question but you really need to read about SQL injection. Commented Aug 16, 2013 at 21:43
  • 2
    For Parameter better use ADO.Net Parameter (SqlParameter) no Self-made strings - to Dan's answer Commented Aug 16, 2013 at 21:51

1 Answer 1

4
SqlCommand sc = new SqlCommand(string.Format("SELECT doklad FROM netpokl WHERE id_dok='{0}'", newIdentity), spojeni);
object obj = sc.ExecuteScalar();
if(obj == null) ; //Should show some message or throw exception
string id_dok = obj.ToString().PadRight(20);
//...
SqlCommand sc2 = new SqlCommand(string.Format("UPDATE kliplat set doklad=@doklad WHERE id='{0}'",newIdentity), spojeni);
//...

BTW: I don't think this is needed. In fact you should check if it's length > 20, then the string should be truncated. Your database table should also use nvarchar(20) instead.

Sign up to request clarification or add additional context in comments.

8 Comments

Hello I tried this but it gave following ex: Reference to an object isn't set to an instance of an object. Any idea where I make mistake?
@Marek this code should replace some lines of yours starting from int id_dok to the end of that line.
I replaced that as you said but still receiving the same exceptions, don't have any idea where the mistake is.
@Marek at which line it highlights?
At ´string id_dok = obj.ToString().PadRight(20);´
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.