2

I have one checkbox control in my web application.And i Connected with the sql server.I declared checkbox datatype as bit. when i am checked the checkbox control it needs to pass bit value.I already execute by following method.

int active;

if (chkboxActive.Checked)

{ active = 1; } 

else

{ active = 0; }

cmd.Parameters.Add("@active", SqlDbType.Bit).Value = active;

It executes well.But i felt it is not a efficient one. Give any other easiest code in short line.

4
  • cmd.Parameters.Add("@active", SqlDbType.Bit).Value = chkboxActive.Checked; Commented May 23, 2014 at 6:37
  • there is no definition for chkboxActive.value. It doesn't have a property like value. this type of error is shown Commented May 23, 2014 at 6:40
  • Yea my bad, changed it to Checked. Commented May 23, 2014 at 6:41
  • ya..this is working fine... thanks a lot Commented May 23, 2014 at 6:48

2 Answers 2

3
cmd.Parameters.Add("@active", SqlDbType.Bit).Value = chkboxActive.Checked; 
Sign up to request clarification or add additional context in comments.

3 Comments

One another question. Is possible to send a opposite value. for example checked=0 unchecked=1
You can use !chkboxActive.Checked for that.
I have same issue but I want to pass the current value like if checked then pass 1 if unchecked pass 0 how ?
0

If you are using Object Relational Mapping, you will be using a property to pass the value:

public bool Active {get; set;}

When you want to save your data to SQL database table for the BIT data type that will be passed from a checkbox you must set the parameters of the sql command to accept bool as bit data and convert it to 1 if true or 0 if false like this:

SqlCommand cmd = new SqlCommand(SqlString, SqlConnection);
cmd.Parameters.Add("@Active", SqlDbType.Bit, Active ? 1:0).Value = Active;

So when the boolean value is passed from the checkbox to the 'Sql Variable` it will be converted to 1 or 0 based on the checkbox.checked property.

xData.Active = CheckBox.Checked;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.