【问题标题】:how to insert multiple checkbox list values into database in single column using c#如何使用c#将多个复选框列表值插入到单列中的数据库中
【发布时间】:2010-08-04 17:01:49
【问题描述】:

我用它来选择一个复选框来选中列 我如何将其转换为多复选框列表到单列 我用了很多方法超过 3 天没有成功

 private void BindCheckBoxList()
    {
        DataTable dt = new DataTable();
        SqlConnection connection = new SqlConnection(GetConnectionString());
        try
        {
            connection.Open();
            string sqlStatement = "SELECT * FROM boby";
            SqlCommand sqlCmd = new SqlCommand(sqlStatement, connection);
            SqlDataAdapter sqlDa = new SqlDataAdapter(sqlCmd);

            sqlDa.Fill(dt);
            if (dt.Rows.Count > 0)
            {
                CheckBoxList1.RepeatColumns = 4; // set the number of columns in the CheckBoxList
                CheckBoxList1.DataSource = dt;
                CheckBoxList1.DataTextField = "Name"; // the items to be displayed in the list items
                CheckBoxList1.DataValueField = "Name"; // the id of the items displayed
                CheckBoxList1.DataBind();

                //Setting the Selected Items in the ChecBoxList based from the value in the database
                //to do this, lets iterate to each items in the list
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    if (!string.IsNullOrEmpty(dt.Rows[i]["IsSelected"].ToString()))
                    {
                        CheckBoxList1.Items[i].Selected = Convert.ToBoolean(dt.Rows[i]["IsSelected"]);
                    }
                }
            }

        }
        catch (System.Data.SqlClient.SqlException ex)
        {
            string msg = "Fetch Error:";
            msg += ex.Message;
            throw new Exception(msg);
        }
        finally
        { 
            connection.Close();
        }
    }

    private void Update(string name, bool isSelected)
    {
        SqlConnection connection = new SqlConnection(GetConnectionString());
        SqlCommand cmd;
        string sqlStatement = string.Empty;
        try
        {
            connection.Open();
            sqlStatement = "UPDATE handymen SET IsSelected = @IsSelected WHERE Name = @BizName";
            cmd = new SqlCommand(sqlStatement, connection);
            cmd.Parameters.AddWithValue("@Name", name);
            cmd.Parameters.AddWithValue("@IsSelected", isSelected);
            cmd.CommandType = CommandType.Text;
            cmd.ExecuteNonQuery();
        }
        catch (System.Data.SqlClient.SqlException ex)
        {
            string msg = "Insert/Update error";
            msg += ex.Message;
            throw new Exception(msg);

        }
        finally
        {
            connection.Close();
        }
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            BindCheckBoxList();
        }
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        string str = string.Empty;

        for (int i = 0; i < CheckBoxList1.Items.Count; i++)
        {
            if (CheckBoxList1.Items[i].Selected)
            {
                str = CheckBoxList1.Items[i].Text;
                Update(str, CheckBoxList1.Items[i].Selected);
            }
        }
        //ReBind the List to retain the selected items on postbacks

        BindCheckBoxList();
    }

【问题讨论】:

  • 那是个坏主意,使用 1:n 关系..

标签: c# asp.net sql database checkboxlist


【解决方案1】:

好吧,如果你要这样做,最好的方法是将它们组合成一个按位组合,也许像这样:

int value = 0;      //or short or long, depending on the number of bits
int bitDegree = 1;  //or short or long, depending on the number of bits

for (int i = 0; i < dt.Rows.Count; i++)
{
    if (!string.IsNullOrEmpty(dt.Rows[i]["IsSelected"].ToString())
        && Convert.ToBoolean(dt.Rows[i]["IsSelected"]))
    {
        value += bitDegree;
    }

    bitDegree *= 2;
}

但是,如果可以,最好在数据库中使用多个 Bit 列,而不是将它们组合起来。

【讨论】:

  • 我有 30 个复选框,我认为我需要这样做 30 次?
  • 好吧,如果它们的所有值都是dt 中的列,那么这个for 循环应该会全部命中。只需确保value 的数据类型和数据库中的相应列至少具有与复选框一样多的位。正则 int 有 32 个,short 有 16 个,long 有 64 个。它们分别匹配 SQL 数据类型 int、smallint 和 bigint。
【解决方案2】:

我个人不会那样做,它的设计很糟糕。我会创建另一个包含所有值的表,而不是尝试将它们全部填充到一个列中。

如果您HAVE可以将它们转换为整数并用逗号分隔?

例如。 1,0,0,1,1 等

【讨论】:

  • 我在 asp.net 中的每个新名称都有 30 个复选框,我如何将它们转换为整数
【解决方案3】:

您是否考虑过使用bit mask?以下是使用所选类别作为示例的解释(不确定类别是否适用于您的情况,但它说明了这个概念):

首先为每个值分配一个二进制数字-

cat1  cat2  cat3 cat4
----  ----  ---- ----
1     2     4    8

接下来,您将在主表中添加一个整数列,我们将其称为选项。当数字转换为二进制时,每个数字将表示是否设置了类别 1、2、3 或 4。示例:

5 = 0101 in binary = cat1 已设置,cat2 未设置,cat3 已设置,cat4 未设置

id | name         | options
---------------------------
1  | name1        | 5
2  | name2        | 2
3  | name3        | 7
4  | name4        | 6

我们现在可以对选项列使用按位运算来确定允许的选项。例子:

当我们不关心其他类别时,要获取所有设置了类别 2 的记录,请执行以下操作:

2 & 选项 = 2

这将返回记录 2,3 和 4。


要获取所有设置了 cat2 和 cat3 的记录,我们将执行以下按位运算:

6 & 选项 = 6

这将返回记录 3 和 4


要获取所有设置了类别 1 和 3 的记录,我们将执行以下按位运算:

5 & 选项 = 5

这将返回记录 1 和 3。


仅限第 3 类集:

4 |选项 = 4


类别 3 未设置:

4 & 选项 = 0


这可能是一个很难掌握的概念,所以如果您有任何问题,请告诉我。在我看来,一旦你掌握了这个概念,这可能是完成你想做的事情的最简单方法。

【讨论】:

  • 我喜欢你的方式,它看起来很简单我如何开始做你能给我2个类别的示例代码,我可以转换它
【解决方案4】:

试试这个

protected void Button1_Click(object sender, EventArgs e)
{
    SqlConnection con = new SqlConnection("Data Source=ANSA-PC\\SQLEXPRESS;Initial Catalog=pms;Integrated Security=True");
    String str = "";

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

        if (CheckBoxList1.Items[i].Selected)
        {

            if (str == "")
            {
                str = CheckBoxList1.Items[i].Text;
            }
            else
            {
                str += "," + CheckBoxList1.Items[i].Text;

            }

        }
    }
    con.Open();
    SqlCommand cmd = new SqlCommand("insert into aa(a)values('" +str + "')", con);
    cmd.ExecuteNonQuery();
    ClientScript.RegisterStartupScript(Page.GetType(), "validation", "<script language='javascript'>alert('ansari:u also got it')</script>");
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-01-05
    • 2015-11-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-07-28
    相关资源
    最近更新 更多