简体   繁体   English

检查是否选中了复选框 - ASP.NET

[英]Check whether the checkbox is checked or not - ASP.NET

I have the following code: 我有以下代码:

(some.aspx.cs) (some.aspx.cs)

        if(Page.IsPostBack)
        {
        bool apple2 = false;
        bool pizza2 = false;
        bool orange2 = false;
        if (apple.Checked)
            apple2 = true;
        if (pizza.Checked)
            pizza2 = true;
        if (orange.Checked)
            orange2 = true;
        }

(some.aspx) (some.aspx)

     <tr>
     <td>Food:</td>
     <td>Apple <input type="checkbox" name="food" id="apple" value="apple" runat="server" />Pizza <input type="checkbox" name="food" id="pizza" value="pizza" runat="server" />Orange <input type="checkbox" name="food" id="orange" value="orange" runat="server" /></td>
 </tr>

Now, i send the Boolean variables to SQL database. 现在,我将布尔变量发送到SQL数据库。 The problem is only with unchecked boxes. 问题只出现在未经检查的方框中。 I mean, when you check some checkboxes it sends it as true (and that's right) but when i uncheck them it remains the same (true). 我的意思是,当你检查一些复选框时,它会将其发送为真(这是正确的)但是当我取消选中它时它保持不变(真实)。

Addition: Why too little? 另外:为什么太少? here's a query...nothing special here 这是一个查询...这里没什么特别的

string q = string.Format(@"UPDATE tblUsers SET ......., apple='{8}', orange='{9}' WHERE id='{10}'", ...., apple2, orange2, id);
lib.sql_query(q); // using my sql library...

the datatype is bit....i tried also with string...but no success 数据类型是位....我也尝试使用字符串...但没有成功

PS - i also tried with Request.Form["apple"], and the uncheck worked...but unfortunately the check didn't...when i check the checkbox it throws me an error: PS - 我也尝试过Request.Form [“apple”],取消选中工作......但遗憾的是检查没有...当我选中复选框时它会抛出一个错误:

Conversion failed when converting the varchar value 'on' to data type bit. 

Somebody? 有人?

So after a long time of combinations and other stuff it worked...Without any javascripts and hidden fields... that's the .cs code 所以经过很长一段时间的组合和其他东西它工作...没有任何javascripts和隐藏的字段...这是.cs代码

        bool apple2 = (Request.Form["apple"] == "on") ? true : false;
        bool orange2 = (Request.Form["orange"] == "on") ? true : false;
        bool pizza2 = (Request.Form["pizza"] == "on") ? true : false;

Unchecked checkboxes are not submitted when a form is posted. 发布表单时,不会提交未选中的复选框。 You will have to write a workaround. 你必须写一个解决方法。

One method would be to have a hidden field that is populated via the javascript of the checkbox. 一种方法是通过复选框的javascript填充隐藏字段。

using System.Data.SqlClient;
using System.Data;

public partial class _Default : System.Web.UI.Page
{
    SqlConnection con = new SqlConnection("Data Source=RND3 " + "\\" + " SQLEXPRESS;Initial Catalog=SSSolutionFiles;Integrated Security=True");
    public void displaygrid()
    {
        SqlDataAdapter da = new SqlDataAdapter("select * from userfile", con);
        DataSet ds = new DataSet();
        da.Fill(ds, "p");
        GridView1.DataSource = ds.Tables["p"];
        GridView1.DataBind();
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        //Label1.Text = txtUserName.Text + "<br>" + txtPassword.Text + "<br>" + txtConfirmPassword.Text + "<br>" + txtConfirmationNumber.Text;
        displaygrid();
        if (!IsPostBack)
            BindDropDownListData();
    }

    public void BindDropDownListData()
    {
        //SqlConnection con = new SqlConnection("Data Source=RND3 " + "\\" + " SQLEXPRESS;Initial Catalog=SSSolutionFiles;Integrated Security=True");
        //SqlConnection mySqlConnection = new SqlConnection();
        {
            try
            {
                con.Open();
                SqlCommand mySqlCommand = new SqlCommand("Select username from userfile ", con);
                SqlDataAdapter mySqlDataAdapter = new SqlDataAdapter(mySqlCommand);
                DataSet myDataSet = new DataSet();
                mySqlDataAdapter.Fill(myDataSet);
                //DropDownList1.DataSource = myDataSet;
                //DropDownList1.DataTextField = "username";
                //DropDownList1.DataValueField = "username";
                //DropDownList1.DataBind();
                CheckBoxList1.DataSource = myDataSet;
                CheckBoxList1.DataTextField = "username";
                CheckBoxList1.DataValueField = "username";
                CheckBoxList1.DataBind();
            }
            catch (Exception ex)
            {
                Label1.Text = ex.Message;
            }
            finally
            {
                con.Close();
            }
        }
    }
    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        SqlCommand cmd = new SqlCommand("insert into userfile values('" + txtUserName.Text + "','" + txtPassword.Text + "','" + txtConfirmPassword.Text + "','" + txtConfirmationNumber.Text + "')", con);
        con.Open();
        cmd.ExecuteScalar();
        displaygrid();
        BindDropDownListData();
    }
    protected void btnUpdate_Click(object sender, EventArgs e)
    {
        SqlCommand cmd = new SqlCommand("update userfile set confirmnumber='" + txtConfirmationNumber.Text + "', password='" + txtPassword.Text + "',confirmpassword='" + txtConfirmPassword.Text + "' where username='" + txtUserName.Text + "' ", con);
        con.Open();
        cmd.ExecuteScalar();
        displaygrid();
    }
    protected void btnDelete_Click(object sender, EventArgs e)
    {
        SqlCommand cmd = new SqlCommand("delete from userfile where username='" + txtUserName.Text + "' ", con);
        con.Open();
        cmd.ExecuteScalar();
        displaygrid();
        BindDropDownListData();
    }
    protected void btnClear_Click(object sender, EventArgs e)
    {
        txtConfirmationNumber.Text = "";
        txtUserName.Text = "";
        txtConfirmPassword.Text = "";
        txtPassword.Text = "";
    }
    protected void CheckBox1_CheckedChanged(object sender, EventArgs e)
    {
        if (CheckBox1.Checked == true)
        {
            foreach (ListItem checkboxitems in CheckBoxList1.Items)
            {
                checkboxitems.Selected = true;
            }
        }
        else if (CheckBox1.Checked == false)
        {
            foreach (ListItem listItem in CheckBoxList1.Items)
            {
                listItem.Selected = false;
            }
        }
    }
}

THis is actually more accurate to get the checked values for an input field with runat="server". 实际上,使用runat =“server”获取输入字段的选中值更准确。

string isAppleChecked = apple.Attributes["checked"] != null && apple.Attributes["checked"] == "checked" ? string isAppleChecked = apple.Attributes [“checked”]!= null && apple.Attributes [“checked”] ==“checked”? "{true}" : "{false}"; “{真假}”;

Firstly I would tidy your code up at the beginning the if statements are unnecessary: 首先,我会在开头整理你的代码,if语句是不必要的:

if (Page.IsPostback)
{
    bool appleSelected = apple.Checked;
    bool pizzaSelected = pizza.Checked;
    bool orangeSelected = orange.Checked;
}

Have you tried using the CheckBox class instead of input? 您是否尝试过使用CheckBox类而不是输入?

<asp:CheckBox id="apple" value="apple" runat="server" Checked="True|False" />
<asp:CheckBox id="pizza" value="pizza" runat="server" Checked="True|False" />
<asp:CheckBox id="orange" value="orange" runat="server" Checked="True|False" />

It should work since the datatype is bit...at least when you pass the bool to a stored procedure. 它应该工作,因为数据类型是位...至少当你将bool传递给存储过程时。

Since you have the SQL update statement in your code, try converting the bool to a 0 or 1. 由于您的代码中包含SQL更新语句,请尝试将bool转换为0或1。

Int16 iApple = (apple2) ? 1 : 0;
Int16 iOrange = (orange2) ? 1 : 0;
string query = string.Format(@"UPDATE tblUsers SET ......., apple='{8}', orange='{9}'    WHERE id='{10}'", ...., iApple, iOrange, id);
lib.sql_query(q);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM