Quote:
this codes work
No, it doesn't even compile.
b.a.Checked = true;
should be
b.Checked = true;
Richard Deeming pointed out the vulnerability to SQL Injection to which your responded
Quote:
thanks man thats so true,but this was just for trying..
Try to get into the habit of using parameterised queries immediately. You won't have to go back and revisit your code and you are more likely to
avoid the trivial errors that can creep in.
SqlCommand cmd = new SqlCommand("select st from tblvl where ID=@id", cn);
cmd.Parameters.AddWithValue("@id", textBox1.Text);
Quote:
but the problem the loop second time or third is not equal then it unchecked it
Have a look at your code again, see
if (sta == a.Text)
{
a.BackColor = Color.Red;
a.Checked = true;
}
else { a.Checked = false; }
The first time around
sta
is the same as a.Text and Checkbox a is checked. But 2nd time around
sta
is the same as b.Text so you immediately uncheck Checkbox a! Get rid of the
else
clauses and move the a.Checked = false; to outside the loop.
a.Checked = false;
b.Checked = false;
c.Checked = false;
foreach (string sta in aray)
{
if (sta == a.Text)
{
a.BackColor = Color.Red;
a.Checked = true;
}
if(sta == b.Text)
b.Checked = true;
if (sta == c.Text)
c.Checked = true;
}
You would have probably spotted this if you had debugged properly - see this article to get up to speed with debugging
Mastering Debugging in Visual Studio 2010 - A Beginner's Guide[
^]
Now to address some of the other issues...Storing multiple values in a single column on the database is never a good idea - as you have discovered, it is a pain trying to get the values back out in a sensible way.
Why not just have 3 bit columns
sta
,
stb
,
stc
where if the value = 0 the corresponding Checkbox should be unchecked and if the value is 1 then it should be Checked. Eg.
using (var cn = new SqlConnection(constr))
{
var cmd = new SqlCommand("select sta, stb, stc from tblvl where ID=@id", cn);
cmd.Parameters.AddWithValue("@id", textBox1.Text);
cn.Open();
var sqld = cmd.ExecuteReader();
if (sqld.Read())
{
a.Checked = (int)sqld["sta"] == 1;
b.Checked = (int)sqld["stb"] == 1;
c.Checked = (int)sqld["stc"] == 1;
if (a.Checked) a.BackColor = Color.Red;
}
cn.Close();
}