getting value 1 from a selected checkbox & saving the value into a database

Hi,

I m new to ASP... I m building a page with few checkboxes & text boxes.. its a simple checklist you can say..

However, what i am looking for is when a check box is checked & the submit button is clicked, the value of that checkbox as 1 should be saved in the database.

How to acheive this... any help would be really appreciated...

Thanks

Aadil

0
aadilm
2/18/2009 5:05:31 PM
asp.net.getting-started 91979 articles. 4 followers. Follow

9 Replies
845 Views

Similar Articles

[PageSpeed] 52

 in the buttons click event look and see if the check boxes are checked and save in the db if so

  if(chk1.Checked) {

         //save in db   

  }


Mike Starkey MCP, MCTS
0
Starkemc
2/18/2009 5:19:48 PM

Hi Aadil

you can refer my article which allows you understand how to execute queries

http://www.aspsnippets.com/post/Parameterized-Queries-ADONet.aspx

to get textbox values

string str = TextBox1.Text;

for checkboxes

if (CheckBox1.Checked)

{

string value = CheckBox1.Text;

}


MAKMark as Answer if this reply helps you
MVP ASP/ASP.Net
MVP ASP/ASP.Net
ASP.Net Hosting : Host DepotMy Site : ASPSnippets
0
mudassarkhan
2/18/2009 5:20:47 PM

Thanks for the information.

I apologize if i have not explained it properly.

For my scenario, i want to insert a value 1 if the check box is checked & if it is not then a value 0 should be inserted into the database....

Hope i m making it clear to understand the scenario...

Please advice.

Thanks

Aadil

0
aadilm
2/18/2009 8:23:48 PM

hello,

if you use a stored proc you can set the default value to 0 and if the parameter is not empty pass the value of 1. you have to loop through your checkboxlist to see which are checked and pass the parameter of 1 if they are. look at the code below and let me know if you need further assistance.

sql:

ALTER PROCEDURE [dbo].[Charges] (

@ID int = NULL,

@ChargeType varchar(50) = NULL,

@Action varchar(10) = 'Continue'

)AS

BEGIN

-- SET NOCOUNT ON added to prevent extra result sets from

-- interfering with SELECT statements.

SET NOCOUNT ON;

 

IF @Action = 'Remove'

BEGIN

DELETE Order_Charges WHERE Order_ID = @ID AND Charge_Type = @ChargeType

END

 

IF @Action = 'Continue'

BEGIN

IF EXISTS (select 1 from Order_Charges WITH (nolock) where order_id = @ID and Charge_Type =@ChargeType)

BEGIN

UPDATE Order_Charges SET Charge_Type = @ChargeType WHERE Order_ID = @ID AND Charge_Type = @ChargeType

END

 

ELSE

BEGIN

INSERT INTO Order_Charges(Order_ID,Charge_Type)

VALUES (@ID,@ChargeType)

END

END

END

here is the code behind...

protected void Button1_Click(object sender, EventArgs e)

{

 

SqlConnection con = new SqlConnection(connectionString);

SqlCommand cmd = new SqlCommand("Charges", con);

cmd.CommandType = CommandType.StoredProcedure;

con.Open();

 

try

{

CheckBoxList chkbx = (CheckBoxList)form1.FindControl("CheckBoxList1");

 

for (int i = 0; i < CheckBoxList1.Items.Count; i++)

{

 

if (chkbx.Items[i].Selected)

{

cmd.Parameters.AddWithValue(
"@ID", Request.QueryString["id"]);cmd.Parameters.AddWithValue("@ChargeType", CheckBoxList1.Items[i].Value.ToString());

cmd.ExecuteNonQuery();

cmd.Parameters.Clear();

}

if (chkbx.Items[i].Selected == false)

{

cmd.Parameters.AddWithValue(
"@ID", Request.QueryString["id"]);

cmd.Parameters.AddWithValue("@ChargeType", CheckBoxList1.Items[i].Value);

cmd.Parameters.AddWithValue("@Action", "Remove");

cmd.ExecuteNonQuery();

cmd.Parameters.Clear();

 

}

}

}

catch

{

ClientScript.RegisterStartupScript(
typeof(Page), "ShowMessage", "<script language='JavaScript'>alert('An error occurred on the app please try again in a few minutes');</script>");

}

finally

{

con.Close();

ClientScript.RegisterStartupScript(
typeof(Page), "ShowMessage", "<script language='JavaScript'>alert('Charges Submitted Thanks..');</script>");

 

}

}

let me know if you have any questions...

0
mitoy75
2/18/2009 9:49:20 PM
You will have to manually use binding and use sql to update. If you are using it in any data aware container we can handle appropriate event handler to modify the value before posting to database. If you could describe what method are you using to post data or post complete source for the page, I may be able to help you more...
Joseph James
www.beforeyoubuy.co.uk
0
josephjames
2/18/2009 9:54:37 PM

Hi Friend,

First take the value in a integer variable like...

int chkValue;
if (CheckBox.Checked)
{
  chkValue = 1;
}
else
{
  chkValue = 0;
}

now insert the chkValue in the database with Ado.Net


Sincerely,
Pradeep Kr. Sharma

Please remember to click “Mark as Answer” on the post that helps you.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

0
Pradeep
2/18/2009 10:38:14 PM

aadilm:

Thanks for the information.

I apologize if i have not explained it properly.

For my scenario, i want to insert a value 1 if the check box is checked & if it is not then a value 0 should be inserted into the database....

Hope i m making it clear to understand the scenario...

Please advice.

Thanks

Aadil

Define a Bit Filed in database table

You can directly pass the value to ur query Checkbox1.Checked

 when true it will store 1 and 0 when false


MAKMark as Answer if this reply helps you
MVP ASP/ASP.Net
MVP ASP/ASP.Net
ASP.Net Hosting : Host DepotMy Site : ASPSnippets
0
mudassarkhan
2/19/2009 4:45:10 AM

Thank you very much for your response.

However... I m new to this... if its possible for you.. can you please explain me as, how to do this....

like how do you set a Bit Field in DB & how to script the checkbox.. so that it stores 1 when its true & it stores a zero when its false...

 

Thanks,

Aadil

0
aadilm
2/24/2009 4:31:58 PM

aadilm:

Thank you very much for your response.

However... I m new to this... if its possible for you.. can you please explain me as, how to do this....

like how do you set a Bit Field in DB & how to script the checkbox.. so that it stores 1 when its true & it stores a zero when its false...

 

Thanks,

Aadil

in the dataabse add a field with bit datatype

and you can refer my site for the code for inserting values


MAKMark as Answer if this reply helps you
MVP ASP/ASP.Net
MVP ASP/ASP.Net
ASP.Net Hosting : Host DepotMy Site : ASPSnippets
0
mudassarkhan
2/24/2009 5:08:04 PM
Reply:

Similar Artilces:

get value from <select> value & display value
hi all, i want these two bold values which are below,  underline value i can get but second bold value i m not avail to get please help.... <select><option value="ma">manoj</option> </select> regard khushak  P.S. if possible then Please with  java script other wise code behind New In .NET World See my post in this thread.  That should take care of you. Peter BrunoneMS MVP, ASP.NETFounder, EasyListBox.comDo the impossible, and go home early....

Retrieve a database value, if its equals to 1 hide a control (getting started)
Hi is it possible to retrieve a value from the database, and if its equals to 1 then hide a control (textbox). The value i am trying to get is here;private void DisplaySelectedRecord(DataView dv) {if (dv[0]["Rate_Active"] != null && dv[0]["Rate_Active"] != System.DBNull.Value)this.CheckBox1.Checked = Convert.ToBoolean(clsDHOC.Nz2ZeroString(dv[0]["Rate_Active"]));     }   And in page load i want it that if Rate_Active is 1 then the textbox is hidden on page load.  Why not create a private field in your class , assign your rat...

How to pass in value to javascript from database or let javascript to get value from database?
I am trying to use google map api to do some web based application.On the map, the javascript needs latitude and longitude from database to draw a marker on page load, I am wondering how can I get the data from database to do that? The map part will be like a image, won't change.Do I need Ajax?Thank you.  hanxiao:I am trying to use google map api to do some web based application.On the map, the javascript needs latitude and longitude from database to draw a marker on page load, I am wondering how can I get the data from database to do that? The map part will be like a image, won&...

Getting value from selected checkbox
I've got a gridview on my web page. In one of my columns I have a template column with a checkbox. My plan is for a user to click on the check boxes, click  the save button, and the results will update my database. I can find the checkboxes which have been selected by:   Dim chkAdd As CheckBox Dim rowCount As Integer rowCount = dgProcedure.Rows.Count Dim i As Integer For i = 0 To (rowCount - 1) chkAdd = CType(dgProcedure.Rows(i).FindControl("ckCompleted"), CheckBox) If chkAdd.Checked = True ...

problem with get value from textbox after get it value in load page
hi every one  i have problem with my web site when i get textbox value in load page   and Changed textbox the page do not take last value .   it take value in load page   this is code:Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)   TextBox1.Text = "aa" End SubProtected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) MsgBox(TextBox1.Text) End Sub   when i press button message write "aa" while i changed the textbox   please if enyone knowen help me &nbs...

how can I get an integer value out of a division that returns a decimal? (get the 1 out of 1.71564)??
I know I am doing somthing wrong because I am not geting the result I want out of this function:Dim week As Integer = Convert.ToInt16((year + dat.DayOfYear + baseday) / 7) I just want to know which week of the year it is which should only be an integer, but as you see I doo a division of the Day of year by 7 which returns 6 times out of 7 a decimal value can anyone help? The DateTime class has functions to do this for you.  I forget the name but look in there.Solutions Architect Coden Enterpriseshttp://www.codenenterprises.com/iblog get week of the year   DateTime d...

How to get value of selected dynamic checkboxes?
Currently I am working with the project which needs dynamically generated checkboxes and i have generated dynamic checkboxes but i am facing problem with getting the vaue of selected checkboxes. I am using asp table and adding rows dynamically and one of the colums contains all the check boxes. I want to give delete option to user, so when they can delete all rows from database which are checked in table. i have created the functions for deleteing rows but only problems is , table rows disappear once i click delete button (post back event). All the checkbox has different id.  How ...

Getting values from datagrid to save in database
I am trying to get the values from a datagrid to save in a database.  I have radiobuttons and checkbox and when I save I want them to go into a dtabase based on a persons SSN.  The following is my button submit click event but it does not work.Private Sub btnSubmit_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSubmit.Click   For Each myDataRow In myDataTable.Rows If Request.Form("chbxPresent" & myDataRow(0)) = "on" Then sql = "insert tblAttendance (intAssignedPersonnelID) " _ & "values (" & myDat...

Query for substring to get some particular value in a string (Get querystring value by sql )
I have a column name URL in Table1 with data like  <a href="/Folder1/view_media_news.cfm?news_media_i=1">August 2002 Factsheet</a>            <a href="/Folder1/view_media_news.cfm?news_media_i=149">March 2002 Newsletter </a>  i need to grab the news_media_i value by sql query  Please any one can help me to get that particular value from string using substring or any other suggestion Thank you in advance SurendraIf this helps mark it as answer surendra_kla:i nee...

get the values reflected from database table as soon as the value changed!
hai, if the admin changes the value at the database table then it should be reflected to all the pages which is viewing that particular record. We should not use any frequent refresh from the browser. The pages get refreshed as soon as the values changed at database. Thanks in advance Bye   I don't think it can be done. web application is stateless, web client (browser) and web server lost connection once content downloaded, the web server can not "Push" content to client, it must be "Pulled" by web client (browser).Richard XinMCAD(charter member),MCDBA,MCSDWeb Site: www.richar...

DropDownLists w/ Database Values - NOT Getting Values
I have a web form for entry and update purposes. On the form, I have some dropdownlists that allows the user to enter one of three options. When users need to update the values in the database, I would like the values from the database to be shown. I believe my logic is correct, but nothing is shown on Page_Load, i.e. the dropdownlists are blank! Here is part of my code: 'Only part of the code is shown for brevity Sub BindData() If Not IsPostBack Then ddlQuestion1.Items.Add(New ListItem("N/A", 1)) ddlQuestion1.Items.Add(New ListItem("Ye...

Get R G & B values from RGB() value
Is there a way to get the seperate Red Green and Blue values from a single rgb() value? Thanks, Daniel. You should be able to do it by reversing out the RGB function. Something along the lines of rgb_value1 = Mod ( rgb_value, 65536 ) blue = ( rgb_value - rgb_value1 ) / 65536 red = Mod ( rbg_value1, 255 ) green = ( rgb_value1 - red ) / 255 That's off the top of my head though. On 28 Jul 2004 05:21:28 -0700, "Daniel Jenkins" <daniel.jenkinsNOSPAM@gacworld.com> wrote: >Is there a way to get the seperate Red Green and Blue values from a single...

Checkbox not getting bind to a bit value in database
I tried to bind a checkbox with a field of type bit (has null values allowed), I get this error. <asp:CheckBox ID="abcCheckBox" runat="server"  Checked='<%# Bind("abc") %>' /> Conversion from type 'DBNull' to type 'Boolean' is not valid Get rid of the nulls in the bit field of the database.  Maybe set the default value to 0.Steve Wellens My blog...

Get the values from pop up to the grid with out saving to the database
HI, In my parent Window Contain a grid and a Link button While I click on the link button a pop up will appear which contains some Fields (textbox) to enter data’s for eg fields are Name, Phone Number and Address and a save button, My issue is When I click on the save button I need to get the values entered in the pop up to the grid with out saving it to the database ,Is Any body have the code to take the value from the pop up to the grid please help me Thanks,  There is one method using javascript to do this        write this javascript in pop win...

Web resources about - getting value 1 from a selected checkbox & saving the value into a database - asp.net.getting-started

Portal:Law/Nominate/Selected article - Wikipedia, the free encyclopedia
Add the article in to a subpage of this portal, such as Portal:Law/Selected article/# , replacing the "#" with the number above the current highest. ...

F8: Facebook’s FbStart Initiative Will Give Selected Developers A $30K Kick-Start
... successful applications is likely a whole lot easier with $30,000 in free tools and services to start off with, and that’s exactly what selected ...

LEGO Shop - The LEGO Technic team has selected the winner... - Facebook
The LEGO Technic team has selected the winner of the Co-Creation Challenge! LEGO will be producing a limited run of 20,000 of this stunning set.... ...

baby365- Grand Doctor Ma Selected Students for iPad on the iTunes App Store
Get baby365- Grand Doctor Ma Selected Students on the App Store. See screenshots and ratings, and read customer reviews.

Selected Cheney Vice Presidential Photographs
... for photos found within these albums are Paul Morse, Karen Ballard, Kimberlee Hewitt, Shealah Craighead, and Chris Greenberg. These selected ...

[iOS Advice] How To Clarify Your Email Replies By Quoting Selected Text - YouTube
Follow me on Twitter: http://www.twitter.com/macmixing Like my Facebook page: http://www.facebook.com/macmixing RATE, COMMENT, SUBSCRIBE! :-) ...

Sait Faik Abasıyanık’s Selected Stories are tales that beguile all for their brevity
The influential Turkish writer's collection of short stories is often bizzare but never boring.

Animal of the Day: Lucius Has Been Selected as the U.K.’s ‘Happiest Cat’
He’s got one blue eye, one green eye and a heart of gold. British mobile phone company O2 recently held some “cat auditions” to find “the UK’s ...

Michael Sam becomes first openly gay player selected in an NFL Draft
Defensive end Michael Sam of the University of Missouri became the first openly gay player to be selected in a National Football League Draft ...

Refugee spinner selected for PM's XI
Fawad Ahmed has gone from asylum seeker to rubbing shoulders with Julia Gillard at The Lodge.

Resources last updated: 11/28/2015 9:41:06 PM