简体   繁体   English

C#-SQL插入值和复选框ID从CheckboxList

[英]C# - SQL Insert Value and ID of checkbox From CheckboxList

The Issue: 问题:

I populate a checkbox list from a SQL table: 我从SQL表填充了一个复选框列表:

public static List<string> populateCheckBoxes(string type)
        {
            List<string> items = new List<string>();
            items.Add("");

            SqlConnection conn = new SqlConnection(connectionString);
            SqlCommand sqlcmd;
            switch (type)
            {
                case "referralorsignposting":
                    sqlcmd = new SqlCommand("SELECT * FROM SWApp_List_Equipment WHERE type = 'Referral or Signposting' ORDER BY order_no, name", conn);
                    break;
                case "actionstaken":
                    sqlcmd = new SqlCommand("SELECT * FROM SWApp_List_Equipment WHERE type = 'Actions Taken' ORDER BY order_no, name", conn);
                    break;
                default:
                    sqlcmd = new SqlCommand("SELECT * FROM SWApp_List_Equipment", conn);
                    break;
            }
            SqlDataAdapter da = new SqlDataAdapter(sqlcmd);
            DataTable dt = new DataTable();
            da.Fill(dt);
            foreach (DataRow dr in dt.Rows)
            {
                items.Add(dr["name"].ToString());
                CheckboxIDRecord = dr["id"].ToString();
                //items.Add(dr["VisitTime"] + " " + dr["PropPostcode"]);
            }

            return items;
        }

I have iterated through each value that is selected in the "checkboxlist" and this inserts each value selected: 我已经遍历了在“复选框列表”中选择的每个值,这将插入每个选择的值:

foreach (var item in saw.actionsTakenCheckBoxList)
                {   //ADD ACTIONS AND REFERRAL 
                    SqlCommand add = new SqlCommand("INSERT INTO SWApp_CheckboxAnswers (SW_ID, Checkbox_ID, Checkbox_Section, Checkbox_Type, Checkbox_Answer) VALUES(@SW_ID,@Checkbox_ID,@Checkbox_Section,@Checkbox_Type,@Checkbox_Answer) ");
                    add.CommandType = CommandType.Text;
                    add.Connection = sqlcon;
                    add.Parameters.AddWithValue("@SW_ID", "");
                    add.Parameters.AddWithValue("@Checkbox_ID", "");
                    add.Parameters.AddWithValue("@Checkbox_Section", "");
                    add.Parameters.AddWithValue("@Checkbox_Type", "");
                    add.Parameters.AddWithValue("@Checkbox_Answer", "");
                    add.Parameters["@SW_ID"].Value = saw.EntryID.ToString();
                    add.Parameters["@Checkbox_ID"].Value = CheckboxIDRecord.ToString();
                    add.Parameters["@Checkbox_Section"].Value = "SmokeDetectionReferral";
                    add.Parameters["@Checkbox_Type"].Value = "";
                    add.Parameters["@Checkbox_Answer"].Value = item.ToString();
                    sqlcon.Open();
                    add.ExecuteNonQuery();
                    sqlcon.Close();
                }

As you can see what i have currently tried only inputs the ID for the first value selected in the Checkboxlist. 如您所见,我当前尝试的操作仅输入在“复选框”列表中选择的第一个值的ID。

The Aim : 目的

The aim is to have insert the value of the checkbox which is "name" and also the "id" of the each item. 目的是插入复选框的值,即“名称”以及每个项目的“ id”。

Research: 研究:

I tried following this article to put the items into an array but ended up with a 'Array was out of bounds of the index' which led me to the second article. 我尝试按照本文的规定将项目放入数组中,但最终出现了“数组超出索引范围”的问题,这使我进入了第二篇文章。

Pass items from checkboxlist to SQL Server table 将项目从复选框列表传递到SQL Server表

Index was out of bounds of array? 索引超出数组范围? c# forms C#表格

I would appreciate any guidance with this. 我对此表示感谢。 Thanks. 谢谢。

I see several issues, rather than attempting to rectify them here is a proposal for how to work this out. 我看到了几个问题,而不是在这里试图纠正它们,是有关如何解决此问题的建议。

The overall picture can be seen in my MSDN code sample on CheckedListBox and SQL-Server which includes an sql script to generate the datbase and data. 可以在我的CheckedListBox和SQL-Server的MSDN代码示例中看到整个图片,其中包括一个用于生成datbase和数据的sql脚本。

https://code.msdn.microsoft.com/Working-with-CheckedListBox-3b765442?redir=0 https://code.msdn.microsoft.com/Working-with-CheckedListBox-3b765442?redir=0

Taken from the link above in Operations.cs, this method gets our data (next code block populates the CheckedListBox) 从上面的Operations.cs链接中获取,此方法获取我们的数据(下一个代码块填充CheckedListBox)

/// <summary>
/// Get all records to show in the CheckedListBox
/// </summary>
/// <returns></returns>
public DataTable GetAll()
{
    var dt = new DataTable();

    using (SqlConnection cn = new SqlConnection { ConnectionString = ConnectionString })
    {
        using (SqlCommand cmd = new SqlCommand { Connection = cn })
        {
            cmd.CommandText = "SELECT id, Description, Quantity, CheckedStatus FROM Products ---WHERE (Quantity > 0)";

            cn.Open();
            dt.Load(cmd.ExecuteReader());

        }
    }

    return dt;

}

Form code 表格代码

/// <summary>
/// Load CheckedListBox from database table
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void Form1_Load(object sender, EventArgs e)
{

    var ops = new Operations();

    // read data from database table
    var dt = ops.GetAll();

    int LastIndex = 0;

    /*
        * Here we iterate the rows in the DataTable while in
        * CoursesCodeSample I set the DataSource of the CheckedListBox
        * to the DataTable. The method shown here has always been the
        * way to go as many indicated that since the DataSource property
        * of the CheckedListBox is not documented it could go away, well
        * many years later it's still here so guess what, it's okay.
        */
    foreach (DataRow row in dt.Rows)
    {
        checkedListBox1.Items.Add(new CheckListBoxItem()
        {
            Description = row.Field<string>("Description"),
            PrimaryKey = row.Field<int>("id"),
            Quantity = row.Field<int>("Quantity"),
            IsDirty = false
        });

        LastIndex = checkedListBox1.Items.Count - 1;
        checkedListBox1.SetItemChecked(LastIndex, row.Field<bool>("CheckedStatus"));

    }

    checkedListBox1.ItemCheck += CheckedListBox1_ItemCheck;

}

From Opertions.cs - insertion method 来自Opertions.cs-插入方法

public void Insert(List<CheckListBoxItem> items)
{
    // optionally used for obtaining new primary key
    //int newIdentifier;

    using (SqlConnection cn = new SqlConnection { ConnectionString = ConnectionString })
    {
        using (SqlCommand cmd = new SqlCommand { Connection = cn })
        {
            // uncomment ending select statement and use commented to get new primary key
            cmd.CommandText = "INSERT INTO Products " + 
                "([Description],Quantity,CheckedStatus) " + 
                "VALUES (@Description,@Quantity,@CheckedStatus); " + 
                "-- SELECT CAST(scope_identity() AS int);";

            cmd.Parameters.Add(new SqlParameter()
                { ParameterName = "@Description", SqlDbType = SqlDbType.NVarChar });
            cmd.Parameters.Add(new SqlParameter()
                { ParameterName = "@Quantity", SqlDbType = SqlDbType.Int });
            cmd.Parameters.Add(new SqlParameter()
                { ParameterName = "@CheckedStatus", SqlDbType = SqlDbType.Bit });
            cmd.Parameters.Add(new SqlParameter()
                { ParameterName = "@CategoryIdentifier", SqlDbType = SqlDbType.Int });


            cn.Open();

            foreach (CheckListBoxItem item in items)
            {
                cmd.Parameters["@Description"].Value = item.Description;
                cmd.Parameters["@Quantity"].Value = item.Quantity;
                cmd.Parameters["@CheckedStatus"].Value = item.Checked;


                //newIdentifier = (int)cmd.ExecuteNonQuery();
                if ((int)cmd.ExecuteNonQuery() > -1)
                {
                    // inserted
                }
                else
                {
                    // failed
                }

            }
        }
    }
}

The above is basic, the commented out code shows (if needed) how to get the new primary key. 以上是基本内容,注释掉的代码显示(如果需要)如何获取新的主键。

Call the method above 调用上面的方法

private void iterateButton_Click(object sender, EventArgs e)
{
    var items = new List<CheckListBoxItem>();

    for (int index = 0; index < checkedListBox1.Items.Count; index++)
    {
        if (((CheckListBoxItem)checkedListBox1.Items[index]).IsDirty)
        {
            items.Add(new CheckListBoxItem()
            {
                PrimaryKey = ((CheckListBoxItem)checkedListBox1.Items[index]).PrimaryKey,
                Checked = checkedListBox1.GetItemChecked(index),
                Description = ((CheckListBoxItem)checkedListBox1.Items[index]).Description
            });
        }
    }

    if (items.Count >0)
    {
        Ops.Insert(items);
    }
}

Finally the class used to populate the CheckedListBox 最后,用于填充CheckedListBox的类

namespace CheckListBoxFromSQL_Server
{
    public class CheckListBoxItem
    {
        /// <summary>
        /// Identifier for database table
        /// </summary>
        public int PrimaryKey;
        /// <summary>
        /// Display member for CheckedListBox and a field in the table
        /// </summary>
        public string Description;
        public int Quantity;
        /// <summary>
        /// Indicates the checked state in the database table and for setting a Checked item in the CheckedListbox
        /// </summary>
        public bool Checked;
        /// <summary>
        /// Used to determine if a item changed after loaded in the CheckedListBox
        /// </summary>
        public bool IsDirty;
        public override string ToString() { return Description; }
    }
}

Hope this is helpful 希望这会有所帮助

I implemented a dictionary for the items to be placed into the checkboxlist. 我实现了将要放入复选框列表中的项目的字典。 This allows me to use the value within the checkbox items and then use the Key in the INSERT to the SQL DB. 这使我可以使用复选框项目中的值,然后在INSERT到SQL DB中使用键。

Dictionary<string, string> referral = new Dictionary<string, string>();

On form load populate the checkboxlist with items from dictionary. 在表单加载时,用字典中的项目填充复选框列表。

private void Section3_Load(object sender, EventArgs e)
        { 
            SqlConnection conn = new SqlConnection(connectionString);
            SqlCommand cmd = new SqlCommand("select Id, name from SWApp_List_Equipment WHERE type = 'referral or signposting' ORDER BY order_no,name", conn);
            conn.Open();
            SqlDataReader dr = cmd.ExecuteReader();

            if (dr.HasRows)
            {
                while (dr.Read())
                {
                    referral.Add(dr["id"].ToString(), dr["name"].ToString());
                }
            }

            foreach (KeyValuePair<string, string> refs in referral)
            {
                box = new CheckBox();
                box.Text = refs.Value.ToString();
                actionsTakenCheckBoxList.Items.Add(box.Text);
                box.CheckedChanged += new EventHandler(this.CheckedChange);
            } 
        }

Insert values into table on Close Button of form. 在窗体的“关闭”按钮上将值插入表中。

private void closeButton_Click(object sender, EventArgs e)
        {
    using (SqlConnection sqlcon = new SqlConnection(connectionString)) {
                    //summary
                    foreach (var item in actionsTakenCheckBoxList.CheckedItems.OfType<string>().ToList())
                    {

                        //ADD ACTIONS AND REFERRAL 
                        SqlCommand add = new SqlCommand("INSERT INTO SWApp_CheckboxAnswers (SW_ID, Checkbox_ID, Checkbox_Section, Checkbox_Type, Checkbox_Answer) VALUES(@SW_ID,@Checkbox_ID,@Checkbox_Section,@Checkbox_Type,@Checkbox_Answer) ");
                        add.CommandType = CommandType.Text;
                        add.Connection = sqlcon;
                        add.Parameters.AddWithValue("@SW_ID", "");
                        add.Parameters.AddWithValue("@Checkbox_ID", "");
                        add.Parameters.AddWithValue("@Checkbox_Section", "");
                        add.Parameters.AddWithValue("@Checkbox_Type", "");
                        add.Parameters.AddWithValue("@Checkbox_Answer", "");
                        add.Parameters["@SW_ID"].Value = entry.entryID.ToString();
                        var myKey = referral.FirstOrDefault(x => x.Value == item.ToString()).Key;
                        add.Parameters["@Checkbox_ID"].Value = myKey;
                        add.Parameters["@Checkbox_Section"].Value = "SmokeDetection";
                        add.Parameters["@Checkbox_Type"].Value = "Referral";
                        add.Parameters["@Checkbox_Answer"].Value = item.ToString();
                        sqlcon.Open();
                        add.ExecuteNonQuery();
                        sqlcon.Close();

                    }
                }
}

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

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