Search code examples
c#sqlsqldatareadergetstring

Check radiobuttons after SqlDataReader


I have 2 radio buttons in a panel and I save their value as numeric (0 and 1) here is the code for insert into SQL:

String typdop="1";
if(rb_a.Checked)typdop="0";
("INSERT INTO zajezd(typdop)values(@typdop")
prikaz.Parameters.AddWithValue("typdop", typdop);

and for reading I use this:

SqlCommand novyprikaz = new SqlCommand("SELECT * FROM zajezd WHERE akce="+nc_zajezd_vyber, spojeni); 
con.Open();
SqlDataReader precti = novyprikaz.ExecuteReader();

if (precti.Read())
{
     try
     {  rb_a.Checked = precti(32);}

the visual studio gives me an error, because I don't know how to change Checked value of rb_a, I would like to read it like this:

If in database is saved 0 - Check rb_a

If 1 I would like to check rb_b

May someone help solve this out? Thanks


Solution

  • Too many details are missing, but you could try this code.

    string cmdText = "SELECT * FROM zajezd WHERE akce=@p1";
    SqlCommand novyprikaz = new SqlCommand(cmdText, spojeni); 
    novyprikaz.Parameters.AddWithValue("@p1", nc_zajezd_vyber);
    spojeni.Open(); 
    SqlDataReader precti = novyprikaz.ExecuteReader();
    if (precti.Read())
    {
       try
       {  
            bool check = Convert.ToBoolean(precti(32));
            if(check) 
                rb_b.Checked = true;
            else
                rb_a.Checked = true;
       }
    }
    

    Please take note; if your nc_zajezd_vyber is not of the correct datatype required by the database field, your query could fail to retrieve anything. AddWithValue assumes the datatype of the parameter from the value passed. If this is not correct....

    For the same reasong (AddWithValue wants the exact datatype expected by the database field, then your insert code should be something like this:

    int typdop=1; 
    if(rb_a.Checked) typdop=0; 
    string cmdText = "INSERT INTO zajezd(typdop)values(@typdop)"; 
    SqlCommand prikaz = new SqlCommand(cmdText,spojeni);
    prikaz.Parameters.AddWithValue("typdop", typdop);
    spojeni.Open();
    prikaz.ExecuteNonQuery();
    ....