0

I need to populate a checkbox in asp C# based on a value of 0 or 1 from my database.

 SqlCommand Comm1 = new SqlCommand("Select Active from dbo.SQLInfrastructure WHERE [Instance] LIKE  '" + label1.Text + "%'", connn);
 connn.Open();
 SqlDataReader DR1 = Comm1.ExecuteReader();


 if (Comm1==1)
 {
     this.activeCheckBox.Checked = false;
 }
 else
 {
     this.activeCheckBox.Checked = true;
 }

 connn.Close();

I believe I am close, this is on the page_load event. This code does not work but conveys what I am trying to accomplish.

Raktim Biswas
  • 4,011
  • 5
  • 27
  • 32

4 Answers4

0

Have a look at this SqlDataReader example

Essentially, before you can use the content of the reader you have to move it to the first record

Also (further to STLDeveloper's comment)... consider using parameterised queries instead of direct values

Scott Perham
  • 2,410
  • 1
  • 10
  • 20
  • I will absolutely use parameterised queries. I wanted to oversimplify it so I could get the code working. Thanks for the comments tho – PoopaSaurasRex Sep 15 '16 at 21:22
0
SqlCommand Comm1 = new SqlCommand("Select Active from dbo.SQLInfrastructure WHERE [Instance] LIKE  '" + label1.Text + "%'", connn);
connn.Open();
SqlDataReader DR1 = Comm1.ExecuteReader();

this.activeCheckBox.Checked = DR1.Read() && DR.GetBoolean(0);

connn.Close();

Also,

This is very much wrong to what you have done over here,

if (Comm1==1){}

since, the SqlCommand object Comm1 cannot have an integer value in it as said by LarsTech in the comments.

Community
  • 1
  • 1
Raktim Biswas
  • 4,011
  • 5
  • 27
  • 32
0

DataAdapter might be an other solution,

SqlDataAdapter adp = new SqlDataAdapter("command",connection);
DataTable dt = new DataTable();
adp.Fill(dt);

if((int)dt.AsEnumerable().First()["Active"] == 1) {
    this.activeCheckBox.Checked = false;
}
else{
    this.activeCheckBox.Checked = true;
}

Hope helps,

Berkay Yaylacı
  • 4,383
  • 2
  • 20
  • 37
0

Take a look at the ExecuteScalar() method of the SqlCommand class:

this.activeCheckBox.Checked = (bool)Comm1.ExecuteScalar;

Also, as STLDeveloper indicates, you should really be using SqlParameters to pass user input into your SQL statement.

Community
  • 1
  • 1
ssis_ssiSucks
  • 1,476
  • 1
  • 12
  • 11