Select SqlCommand return char
.net, c#, sql, sql-server, winforms
Solution
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.
Problem
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?