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

时间:2010-05-25 14:58:24

标签: c# asp.net

我有以下代码:

(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)

     <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>

现在,我将布尔变量发送到SQL数据库。问题仅出在未选中框中。我的意思是,当你检查一些复选框时,它会将其发送为真(这是正确的)但是当我取消选中它时它保持不变(真实)。

增加: 为什么太少? 这是一个查询......这里没什么特别的

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...

数据类型是位....我也尝试使用字符串...但没有成功

P.S。 - 我也尝试过Request.Form [“apple”],取消选中工作......但不幸的是检查没有...当我选中复选框时它会抛出一个错误:

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

有人?

6 个答案:

答案 0 :(得分:7)

所以经过很长时间的组合和其他东西它起作用...没有任何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;

答案 1 :(得分:1)

发布表单时未提交未选中的复选框。你必须写一个解决方法。

一种方法是使用隐藏字段通过复选框的javascript填充。

答案 2 :(得分:0)

首先,我会在开头整理你的代码,if语句是不必要的:

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

您是否尝试使用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" />

答案 3 :(得分:0)

它应该工作,因为数据类型是位...至少当你将bool传递给存储过程时。

由于您的代码中有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);

答案 4 :(得分:0)

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;
            }
        }
    }
}

答案 5 :(得分:0)

使用runat =&#34; server&#34;来获取输入字段的选中值实际上更准确。

string isAppleChecked = apple.Attributes [&#34; checked&#34;]!= null                 &安培;&安培; apple.Attributes [&#34;已检查&#34;] ==&#34;已检查&#34; ? &#34; {TRUE}&#34; :&#34; {false}&#34;;