I am tring to find a better why to do this. I store data in the SQL Server about whether a checkbox was checked or not and the users can come back to the page and alter it as needed. This is the code for Inserting the data. It uses Stored Procedures and I will cut out all unessary code.
myCommand.Parameter.Add("@.CheckBox", myConnection);
That Records it and I use this to retrieve it.
while (myDataReader.Read())
{
string strChecked = myDataReader["Test"];
if ( strChecked == "1" )
{
cbxPhysicalExam.Checked = true;
}
else
{
cbxPhysicalExam.Checked = false;
}
}
This work but I would much rather do this...
while (myDataReader.Read())
{
cbxPhysicalExam.Checked = myDataReader["Test"].ToString();
}
Does anyone know how to do this?
Much Thanks,
RogerDepends on the type you're using in the database. Typical, for a boolean value (that's the case for checkboxes) you use the SQL Server type 'bit'. This returns a 0 or 1 value which can be casted to a boolean value.
Hope this helps?|||OK thats what I use... but how do I code it on the return... It will not compile like this...
cbxExample.Checked = myDataReader["Example"];
I get this on attempt to compile...
Cannot implicitly convert type 'object' to 'bool'
OK... maybe I need to Explicitly convert. I do not know how convert 1 - true and 0 - false|||Yes I see, maybe I was not clear enough in my answer. The bit type in the SQL Server is far more efficient to work with when doing queries etc. How to convert 1 to true and 0 to false? You may use something like this:
cbxExample.Checked = myDataReader["Example"].ToString() == "1";
which will do the job.|||I tried that and it didn't work... Here is all the code
SQL SERVER Table - TEST
Columns - ID int - Test bit
Store Proc For Select
CREATE PROCEDURE dbo.sp_Test
AS
Select * From Test
GO
Store Proc For Insert
CREATE PROCEDURE dbo.sp_TestIns (
@.Testbit )
AS
Insert Into Test (
Test
)
Values (
@.Test
)
GO
Code Behind Page
void SaveClicked()
{
SqlCommand myCommand = new SqlCommand("sp_TestIns", myConnection);
myCommand.CommandType = CommandType.StoredProcedure;
myCommand.Parameters.Add("@.Test", cbxText.Checked);
myCommand.Connection.Open();
myCommand.ExecuteNonQuery();
myCommand.Connection.Close();{
}void Fill()
{
SqlCommand myCommand = new SqlCommand("sp_Test", myConnection);
myCommand.CommandType = CommandType.StoredProcedure;
myConnection.Open();
SqlDataReader myDataReader;
myDataReader = myCommand.ExecuteReader();
while (myDataReader.Read())
{
cbxPhysicalExam.Checked = myDataReader["Test"].ToString() == "1";
}
myDataReader.Close();
myConnection.Close();
}
THis doesn't work... what am I doing wrong?|||I figured it out... Thank you for your help...
cbxTest.Checked = (bool)myDataReader["Test"];
Thanks Again...
Roger
No comments:
Post a Comment