【问题标题】:How to store checkedbox item/s into a string array in C#?如何将复选框项目存储到 C# 中的字符串数组中?
【发布时间】:2018-03-28 18:33:02
【问题描述】:

如何存储复选框列表中选中的项目?我没有课,所以我不能使用 ListItems。我的复选框列表是使用我的数据库 (MS Access) 填充的。

connection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
command.CommandText = @"SELECT CONTENT FROM " + tab + " GROUP BY CONTENT ORDER BY MIN(CHAP)";
OleDbDataAdapter dAdap = new OleDbDataAdapter(command);
DataSet dSet = new DataSet();
dAdap.Fill(dSet);
for (int i = 0; i < dSet.Tables[0].Rows.Count; i++)
{
    chkList.Items.Add(dSet.Tables[0].Rows[i][0].ToString()); //This is the part where the items are populated
}
connection.Close();

使用 foreach 编辑

foreach (string chk in chkList.CheckedItems)
{
    MessageBox.Show(chk.ToString()); //This gets every string checked, but one after another
    top = chk;
}

我的查询

"SELECT TOP " + num + " QUESTION,C1,C2,C3,C4,ANSWER,CONTENT FROM " + tab + " WHERE CONTENT = '" + top + "'"

它只查询最后检查的项目。

编辑以计算检查的项目

MessageBox.Show(chkList.CheckedItems.Count.ToString());

string[] topic = new string[chkList.CheckedItems.Count];
for (int i = 0; i < topic.Length; i++)
{
    topic[i] = //How to get the text for each checked items?                
}

【问题讨论】:

  • 您是否从您的数据库中获取任何数据?
  • 那么,您的代码的真正问题是什么?
  • @Sasha,当我使用组合框时,是的,我可以获取数据。但我会将其更改为清单,以便我可以选择多个数据。问题是我不知道如何获得检查的项目。我想我是否可以将字符串存储到一个数组中并加入它。还是有其他办法?
  • @Ferus7,发布的代码没有问题。但是我仍然缺乏如何获得检查项目。我不知道在哪里可以添加代码来获取选中的项目。
  • @JepherJohnChang 你想从哪里得到它们?你能指出错误的确切位置吗?

标签: c# arrays string


【解决方案1】:

也许这可以帮助你:

connection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
command.CommandText = @"SELECT CONTENT FROM " + tab + " GROUP BY CONTENT ORDER BY MIN(CHAP)";
OleDbDataAdapter dAdap = new OleDbDataAdapter(command);
DataSet dSet = new DataSet();
dAdap.Fill(dSet);
string[] chkList = new string[dSet.Tables[0].Rows.Count]
for (int i = 0; i < dSet.Tables[0].Rows.Count; i++)
{
    chkList[i]=dSet.Tables[0].Rows[i][0].ToString(); //This is the part where the items are populated
}
connection.Close();

【讨论】:

  • 能否请您指出如何为什么这解决了OPs问题?仅仅粘贴一些代码并不是一个好的答案。
  • 如果我错了,请纠正我。 string[] chkList = new string[dSet.Tables[0].Rows.Count] 会创建一个行数数组吗?如果该项目被选中,这也会得到吗?
  • 在此代码中,如果您想将数据存储在数组中,我们将获得一个字符串数组,用于将您的数据存储在此数组中,这可以帮助您。否则你的意思不是这个说我!
  • 如何使 chkList 本地化应该对他有帮助?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-11-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多